In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to create a C # expression tree Expression". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is an expression tree?
The expression tree represents the code in a tree data structure, where each node is an expression, such as method calls and x
< y 这样的二元运算等。可以对表达式树中的代码进行编辑和运算。 这样能够动态修改可执行代码、在不同数据库中执行 LINQ 查询以及创建动态查询。 表达式树还能用于动态语言运行时 (DLR) 以提供动态语言和 .NET 之间的互操作性,同时保证编译器编写员能够发射表达式树而非 Microsoft 中间语言 (MSIL)。 这段话是来自官网( [表达式树 (C#) | Microsoft Docs](表达式树 (C#) | Microsoft Docs) )的定义。 在 C# 中,我们可以通过 Expression 的方式来手动创建表达式树,比如: [HttpGet]public IActionResult _Expression(){ // 查询 年龄Age 大于 18 的元素 Expression expression1 = x =>X.Age > 18; return Ok ();}
So, the tree structure of the expression x.Age > 18 looks like this:
Through the way that Visual Studio comes with viewing variables or adding monitoring, we can find that the root node (NodeType) of the tree is GreaterThan, the left node (Left) is x.Age, and the right node (Right) is 18. So you can probably draw a tree structure from this.
Finally, with this tree structure, C # can help us compile the expression into a specific SQL execution statement.
If you want to see the structure of the expression tree more clearly, you can nuget an ExpressionTreeToString to convert the expression structure into a string
PM > Install-Package ZSpitz.Util-Version 0.1.116Expression expression = u = > u.Age > = 18 Type treeStr = expression.ToString ("Object notation", "C#"); / / output to the following string var u = new ParameterExpression {Type = typeof (User), IsByRef = false, Name = "u"} New Expression {NodeType = ExpressionType.Lambda, Type = typeof (Func), Parameters = new ReadOnlyCollection {u}, Body = new BinaryExpression {NodeType = ExpressionType.GreaterThanOrEqual, Type = typeof (bool), Left = new MemberExpression {Type = typeof (int), Expression = u, Member = typeof (User) .GetProperty ("Age")} Right = new ConstantExpression {Type = typeof (int), Value = 18}}, ReturnType = typeof (bool)} Expression and Func
Expression stores operational logic, which can be saved as an abstract grammar tree (AST), and can be obtained dynamically at run time.
Func only stores the results and cannot be saved as a syntax tree, nor can it dynamically obtain the operation logic.
So, in EFCore, when using expressions to query database data, we should choose Expression over Func, because using Func, we can't actually convert the expressions in Func into SQL, but filter the conditions in Func in memory after all the data is loaded into memory.
To put it simply, to filter data older than 18 in the User table, you can write it in these two ways
/ / this way of writing, the actual generated SQL statement is something like SELECT * FROM User as T WHERE T.age > 18Expression expression1 = x = > x.Age > 18dbContext.User.Where (expression1). ToList (); / / the generated statement is like SELECT * FROM User, and then after all the data in the User table is loaded into memory, filter Func func1 = x = > x.Age > 18 after age > 18 DbContext.User.Where (func1). ToList (); create expression tree through code
ParameterExpression
BinaryExpression
MethodCallExpression
ConstantExpression
Almost none of these classes provide constructors, and all properties are almost read-only. Therefore, we generally do not create instances of these classes directly, but call the static methods of the Expression class, such as Parameter, MakeBinary, Call, Constant, and so on. These static methods are generally called factory methods to create the expression tree, and the properties are set by the method parameter class.
Dynamically build the expression: U = > u.Age > = 18; from the code
General build steps:
Create a ParameterExpression first
Then build it step by step from the inside out.
First left node (Left)
Rear right node (Right)
Then the Body node
Splice it into Expression
Public IActionResult GetUserByManual_Expression () {ParameterExpression parameterExpression = Expression.Parameter (type:typeof (User), name: "u"); ConstantExpression right = Expression.Constant (18); MemberExpression left = Expression.MakeMemberAccess (parameterExpression, member: typeof (User) .GetProperty ("Age")); BinaryExpression body = Expression.GreaterThanOrEqual (left, right); Expression expression = Expression.Lambda (body, parameters: parameterExpression); var data = _ userService.GetUsers (expression) Return Ok (new {code = 200, msg = "OK", data});} "how to create a C# expression tree Expression" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 241
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.