In the data query, we often encounter the need to dynamically build query conditions. Implementing this requirement with LINQ can be a bit more cumbersome than the previous concatenation of SQL statements. This paper introduces 3 kinds of methods of dynamically constructing query conditions in runtime. The example in this article ultimately implements the same functionality, searching for items in the Northwind database Customers table with CompanyName columns with any element in the keywords. Keywords is a string array whose length is indeterminate at compile time. Ideas and method descriptions are written in code comments.
1. Expression tree
1 public static ienumerable<customers> GetCustomersFunc1 (string[] keywords)
2 {
3 Dat Aclassesdatacontext dc = new Dataclassesdatacontext ();
4
5//Create a static type customers parameter Expression
6 parameterexpression c = Expression.parameter (typeof (Custome RS), "C");
7
8//Create an expression that is constant equals false, used with the following expression to set
9 Expression condition = Expression.constant (false);
10 foreach (string keyword in keywords)
One {
12//This expression is used to determine whether the value of the CompanyName property of a customers class is wrapped Contains the keyword keyword
Expression con = expression.call (
Expression.property (c, typeof (Customers). GetProperty ("CompanyName")),
typeof (String). GetMethod ("Contains", new type[] {typeof (String)}),
expression.constant (keyword));
18
is logical or operational with the previous condition expression.
19//If the item you are looking for needs to contain all the keywords in keywords, you can use Expression.and (con, condition) 20//And the ExpressIon condition = Expression.constant (false);
21//change to Expression condition = Expression.constant (true);
Condition = expression.or (con, condition);
23}
25
//Create a delegate with a Customers class as a parameter and return a bool type of
Expression<func<customers, bool>> end = E Xpression. Lambda<func<customers, bool>> (condition, new parameterexpression[] {c});
28
//query using the conditions just built
var result = DC. Customers.where (end);
return result;
31}