動態拼接Lambda表示式-表示式目錄樹動態構建及修改-----表示式樹的訪問過程,並轉化成sql語句
阿新 • • 發佈:2020-12-02
程式碼如下:
#region 表示式樹的訪問過程,並轉化成sql語句 /// <summary> /// 訪問 表示式樹 Expression<Func<MyClass, bool>> expressionFunc = x => x.Age > 5 && x.Id == 8; /// 並轉化成sql語句 select * from MyClass where age > 5 and id = 8 /// </summary> public class OperatorExpressionToSql : ExpressionVisitor {/// <summary> /// 存放Expression表示式樹的內容 /// </summary> public Stack<string> StackSet { get; set; } public OperatorExpressionToSql() { StackSet = new Stack<string>(); StackSet.Push("("); }/// <summary> /// 修改表示式樹的形式 /// </summary> /// <param name="expression"></param> /// <returns></returns> public Expression Modify(Expression expression) { //base.Visit(expression);//if (expression is BinaryExpression binary) //{ // if (binary.NodeType == ExpressionType.Add) // { // var left = base.Visit(binary.Left); ; // var right = base.Visit(binary.Right); // var result = Expression.Subtract(left, right); // return result; // } //} return base.Visit(expression); } /// <summary> /// 表示式樹的二元操作 /// </summary> /// <param name="node"></param> /// <returns></returns> protected override Expression VisitBinary(BinaryExpression node) { if (node.NodeType == ExpressionType.AndAlso) { base.Visit(node.Left); StackSet.Push("and"); base.Visit(node.Right); //var result = Expression.Subtract(left, right); //return result; StackSet.Push(")"); } else if (node.NodeType == ExpressionType.GreaterThan) { if (node.Left is MemberExpression member) { StackSet.Push(member.Member.Name); } StackSet.Push(">"); if (node.Right is ConstantExpression constant) { StackSet.Push(constant.Value.ToString()); } } else if (node.NodeType == ExpressionType.Equal) { if (node.Left is MemberExpression member) { StackSet.Push(member.Member.Name); } StackSet.Push("="); if (node.Right is ConstantExpression constant) { StackSet.Push(constant.Value.ToString()); } } //StackSet.Push(node.Value.ToString()); return node; //return base.VisitBinary(node); } /// <summary> /// 表示式樹的常量操作 /// </summary> /// <param name="node"></param> /// <returns></returns> protected override Expression VisitConstant(ConstantExpression node) { StackSet.Push(node.Value.ToString()); return base.VisitConstant(node); } } /// <summary> /// 測試表達式樹的訪問過程,並轉化成sql語句 /// </summary> public static void TestDynamicExpressionToSql() { //訪問 表示式樹 Expression<Func<MyClass, bool>> expressionFunc = x => x.Age > 5 && x.Name == "8"; /// 並轉化成sql語句 select * from MyClass where age > 5 and id = 8 OperatorExpressionToSql visitor = new OperatorExpressionToSql(); var expression = visitor.Modify(expressionFunc.Body); var d = string.Join(' ', visitor.StackSet.Reverse().ToArray()); //while (visitor.StackSet.Count > 0) //{ // Console.WriteLine($"結果:{visitor.StackSet.Pop()}"); //} Console.WriteLine($"結果:{d}"); } #endregion