How to convert func to expression (C #)

Source: Internet
Author: User

After this article is written, I found that there are a lot of discussions on expresstion and func on the Internet. I don't want to check them. I have read these articles in the same way, but I am still going deeper:

Http://fascinatedwithsoftware.com/blog/post/2012/01/10/More-on-Expression-vs-Func-with-Entity-Framework.aspx

Http://fascinatedwithsoftware.com/blog/post/2011/12/02/Falling-in-Love-with-LINQ-Part-7-Expressions-and-Funcs.aspx

Http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct

Http://q.cnblogs.com/q/37952/

For more information, see the following two extension methods:

public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

This is the where method that we often use when using LINQ and entityframework. I have never paid attention to the differences between them:

After passing in func, we get the ienumerable object, and pass in expression to get the iqueryable object. What is the difference between them?

Example:

I want to check all the products with productid greater than 15 in the products table of the northwind database. In a very simple sentence, to pass in FUNC AND EXPRESSION separately, we make the following encapsulation:

// Accept the func parameter and return ienumerableprivate ienumerable <t> fetchdata2 <t> (func <t, bool> F) where T: Class {var context = new northwindentities (); return context. set <t> (). where (f);} // accepts the expression <func> parameter and returns iqueryableprivate iqueryable <t> fetchdata <t> (expression <func <t, bool> F) where T: class {var context = new northwindentities (); Return context. set <t> (). where (f );}

Separate calls:

FetchData2<Products>(m => m.ProductID > 15).ToList();FetchData<Products>(m => m.ProductID > 15).ToList();

The results are of course no different. What we need is SQL:

-- Query with func as the parameter. The where statement select [extent1] is not generated. [productid] as [productid], [extent1]. [productname] as [productname], [extent1]. [supplierid] as [supplierid], [extent1]. [categoryid] as [categoryid], [extent1]. [quantityperunit] as [quantityperunit], [extent1]. [unitprice] as [unitprice], [extent1]. [unitsinstock] as [unitsinstock], [extent1]. [unitsonorder] as [unitsonorder], [extent1]. [reorderlevel] as [reorderlevel], [extent1]. [Discontinued] as [Discontinued] from [DBO]. [products] as [extent1] -- Query with expression as the parameter, where statement select [extent1] is generated as expected. [productid] as [productid], [extent1]. [productname] as [productname], [extent1]. [supplierid] as [supplierid], [extent1]. [categoryid] as [categoryid], [extent1]. [quantityperunit] as [quantityperunit], [extent1]. [unitprice] as [unitprice], [extent1]. [unitsinstock] as [unitsinstock], [extent1]. [unitsonorder] as [unitsonorder], [extent1]. [reorderlevel] as [reorderlevel], [extent1]. [Discontinued] as [Discontinued] from [DBO]. [products] as [extent1] Where [extent1]. [productid]> 15

This result is amazing. When you pass in func, you can retrieve all the data in the memory and then perform enumeration filtering ~~~, This is a big surprise. We can see that we must pay attention to this point during normal development.

The comparison is not complete yet, because the general enterprise framework or interface will not expose the underlying database operations, and the external operations are all business methods, such as the above example, to obtain all products whose IDs are greater than a certain value, we assume that the following method (Interface) is exposed ):

// Obtain the product list private ienumerable <Products> getproducts (int id) {var datas = fetchdata <Products> (M => M. productid> ID); Return datas ;}

Call:

 GetProducts(15);

Generate SQL:

exec sp_executesql N'SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], [Extent1].[SupplierID] AS [SupplierID], [Extent1].[CategoryID] AS [CategoryID], [Extent1].[QuantityPerUnit] AS [QuantityPerUnit], [Extent1].[UnitPrice] AS [UnitPrice], [Extent1].[UnitsInStock] AS [UnitsInStock], [Extent1].[UnitsOnOrder] AS [UnitsOnOrder], [Extent1].[ReorderLevel] AS [ReorderLevel], [Extent1].[Discontinued] AS [Discontinued]FROM [dbo].[Products] AS [Extent1]WHERE [Extent1].[ProductID] > @p__linq__0',N'@p__linq__0 int',@p__linq__0=15

Let's take a look at the difference from the SQL statement generated above. It has become a stored procedure.

Well, there is no question here. I just mentioned several differences in different syntaxes, but why do I have my title? Because it comes from an encapsulation at the underlying layer of my project:

IEnumerable<T> GetEntities(Func<T, bool> exp);

Obviously, I used func to pass the parameter, and you know the result. So I began to look for the func to convert expression method. I searched for it again and used various conversion methods, the following two statements are true:

Expression<Func<Products, bool>> g = m => m.ProductID > 15;Func<Products, bool> t = m => m.ProductID > 15;

However, it is not easy to convert t to G. Let's take a look at it. Since the implementation body is the same, that is, the Declaration is different. Can we directly change the parameter declaration? As demonstrated above, it takes effect directly without any hard encoding.

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.