In c #, Expression expressions are used to solve queries similar to select in SQL.

Source: Internet
Author: User

We often encounter some special requirements in projects. For example, the drop-down box is checked, and the query conditions are spliced according to the option in the drop-down box.

After you see this picture, you will surely say that this is very simple.

Combine all the options into "1-3" and "5-9" and put them behind the words in.

This is indeed logically correct, but have you ever thought about this problem? excessive coupling with the business can solve it?

The current demand sacrifices code elegance and maintainability.

 

In fact, the purpose of this article is to use Expression expressions to implement an elegant solution in the linq query,

At the same time, we will also give you an idea of concatenating SQL statements using expressions.

 

Code first

Public static Expression <Func <T, bool> GetConditionExpression <T> (string [] options, string fieldName)
{
ParameterExpression left = Expression. Parameter (typeof (T), "c"); // c =>
Expression expression = Expression. Constant (false );
Foreach (var optionName in options)
{
Expression right = Expression. Call
(
Expression. Property (left, typeof (T). GetProperty (fieldName), // c. DataSourceName
Typeof (string). GetMethod ("Contains", new Type [] {typeof (string)}), // reflection using the. Contains () method
                          Expression.Constant(optionName)           // .Contains(optionName)
);
expression = Expression.Or(right, expression);//c.DataSourceName.contain("") || c.DataSourceName.contain("")
}
Expression<Func<T, bool>> finalExpression
= Expression.Lambda<Func<T, bool>>(expression, new ParameterExpression[] { left });
return finalExpression;
}

I want to describe the code in reverse push mode. In fact, the purpose of our query is to achieve this effect, someList. where (c => c. name. contains ("someName") | c. name. contains ("someName") | ...)

1. first, determine the expression to be returned, based on experience. the following Expression <Func <T, bool> is required after where, so the return type of the method can be determined.

2. the next task is to splice similar to c => c. name. for expressions like Contains (""), according to the principle from left to right, the expression parameter c on the left is well understood as T, so the parameter of this expression is done,

The Expression. Parameter method can be used to reflect the type and map it to the anonymous variable "c" in the Expression (it can also be understood as encapsulating the Parameter constant into an Expression)

3. Next, splice the right side of the expression

Take a closer look at this code.

Expression right = Expression. Call

(

Expression. Property (left, typeof (T). GetProperty (fieldName), // c. DataSourceName is an attribute of c obtained by reflection first.

Typeof (string ). getMethod ("Contains", new Type [] {typeof (string)}), // declare a string. contains method c. CENAME. contains () Reflection usage. contains () method

Expression. Constant (optionName) // c. javascename. Contains (optionName) Encapsulation Constant

);

Why use Expression. Call?

(Because c. Name. contains belongs to the string. contains () method, we must encapsulate the method into an Expression. The function of Expression. Call is to encapsulate the method into an Expression)

At this time, you will ask contains what? Although the Constant option is of the string type, it still needs to be encapsulated into an Expression. Expression. Constant (optionName) plays a role in encapsulating constants.

So c => c. attribute. the ins (constant) Expression is fixed, but there is still a problem: how to add "|", clever you already have the answer, Expression. or ()

 

4. The last step is of course critical, just as the product needs to be packaged and combined through the pipeline, and the expressions are no exception:

Expression. Lambda <Func <T, bool> (expression, new ParameterExpression [] {left });

For the entire Expression, the left side is the parameter Expression (ParameterExpression), Expression. Lambda is the => symbol, and the right side Expression and parameter Expression are combined using the lambda symbol.

 

In this way, you only need to input a string array to implement the select in effect similar to that in SQL,

Many may ask: Can I use a custom expression to splice SQL statements?

The answer is yes. However, if the business logic is complex and difficult to grasp, we recommend that you use ado to implement it.

Related Article

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.