Lambda dynamically attaches conditions and sorting statements (which can be used for LINQ to SQL)

Source: Internet
Author: User

A common case is that multiple conditions or sorting statements need to be attached to the database to obtain conditions by using LINQ-to-SQL or Lambda (Entity Framework ).

Take name = "John" age = 23 as an Example

First, define a concept. For lambda, the following two expressions are equivalent.

1. List. Where (P => P. Name = "John" & P. Age = 23)

2. List. Where (P => P. Name = "John"). Where (P => P. Age = 23)

Lambda expressions only create a method definition and are not actually executed.

The real execution usually takes data only when the tolist () method (ienumerable <t>) is executed.

Lambda expressions support concatenating multiple small expressions as shown above.

If there are multiple conditions, you only need to add the where expression all the time.

 

The second question:CodeAll are written to death. How can we filter information through string-type key-value pairs submitted on the web?

For example, the data we receive is often "name": "John", "Age" = "23"

You cannot write the following code:

 

Code

  VaR list  =  Context;
If (Forms. containskey ( " Name " ))
{
List. Where (P
=> P. Name = Forms [ " Name " ]);
}
If (Forms. containskey ( " Age " ))
{
List. Where (P
=> P. Age = Convert. toint32 (Forms [ " Age " ]);
}
VaR data
= List. tolist ();

These codes are not only not good in scalability... but you need to add a code that is fast with a large workload and prone to bugs when you add a condition.

 

The ideal practice should be the same as the following (note that the conditions are often complex when the where condition is used for filtering, such as age = 10, age> 10, name. startwith ("Zhang"). In fact, the following method is not used for filtering conditions:

In practice, orderby age DESC and name ASC are usually used as sorting conditions)

 
   Foreach(VAR itemInForms. Keys)
{
List. Where (build condition...); // dynamically attaches all conditions here
}

 

Then, how can we create an expression based on known attribute names and values of the string type? The code for dynamically creating expressions is as follows.

 

Code

  VaR Property  =     Typeof  (Tsource). getproperty (item );
VaR parameter
= Expression. parameter ( Typeof (Tsource ), " P " );
VaR propertyaccess
= Expression. makememberaccess (parameter, property );
VaR orderbyexp
= Expression. Lambda (propertyaccess, parameter );


If (Message. Sort [item] = Pagesortction ction. ascending) // Determines whether the search criteria are applied in ascending or descending order. If the search criteria are applied, the system determines whether to use => <like or something else.
{
Methodcallexpression resultexp
= Expression. Call ( Typeof (Queryable ), " Orderby " , New Type [] { Typeof (Tsource), property. propertytype}, list. expression, expression. Quote (orderbyexp ));
List
= List. provider. createquery < Tsource > (Resultexp );
}
Else
{
Methodcallexpression resultexp
= Expression. Call ( Typeof (Queryable ), " Orderbydescending " , New Type [] { Typeof (Tsource), property. propertytype}, list. expression, expression. Quote (orderbyexp ));
List
= List. provider. createquery < Tsource > (Resultexp );
}

Instead of using list = List. orderby (P => orderbyexp), use expression. Call to combine statements.

Although the final results of the two are the same, the former will load the data locally and then filter it, Because Entity Framework cannot directly resolve this dynamic expression to SQL.

The real logic is to construct a where or order expression based on each condition and sort expression and attach it to the current Lambda expression one by one.

 

Performance problems:

Considering the Application Scenario of Entity Framework, there is also the weight problem (in fact, Database Operations consume more performance than the dynamic expressions here). This kind of performance loss is ideal.

 

Exception:

If the input string is not actually a type attribute, for example, if a lastname is passed and the class does not actually have this attribute, an exception is thrown.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.