简体   繁体   English

使用Entity Framework和LINQ选择和过滤数据

[英]Selecting and filtering data using Entity Framework and LINQ

Suppose I have the following query: 假设我有以下查询:

 context.Orders.Where(predicate).Select(x => new { propA = x.PropA, propB = x.PropB}).ToList();

Does this perform both the where and select functions at the DB/ORM level, returning only the data that satisfy both expressions, or would it return all the results that satisfy the predicate and then perform the select on those? 这是在DB / ORM级别上同时执行where和select函数,仅返回同时满足两个表达式的数据,还是返回所有满足谓词的结果,然后对它们执行选择?

Thanks. 谢谢。

You are using IQueryable.Select method. 您正在使用IQueryable.Select方法。 So it is definitely translated into SQL.From the docs 因此,它肯定是翻译成SQL.From的文档

The Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>>) method generates a MethodCallExpression that represents calling Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>> ) itself as a constructed generic method. Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>>)方法生成代表调用Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>>的MethodCallExpression Select<TSource, TResult>(IQueryable<TSource>, Expression<Func<TSource, TResult>> )本身作为构造的泛型方法。 It then passes the MethodCallExpression to the CreateQuery(Expression) method of the IQueryProvider represented by the Provider property of the source parameter. 然后,它将MethodCallExpression传递到由源参数的Provider属性表示的IQueryProviderCreateQuery(Expression)方法。

You can verify this by using a profiler.Or, try calling an unsupported method in the Select and you will get an exception that says linq to entities does not recognize the method X , that also verifies the Select is converted to SQL and not executed in the memory. 您可以使用探查器进行验证,或者尝试在Select调用不受支持的方法,并且会收到一个异常,表明linq to entities does not recognize the method X ,这也验证了Select是否已转换为SQL并且未在中执行记忆。

It will do both at the DB/ORM level. 它将同时在DB / ORM级别上执行。 Results of your query fetched only when you enumerating your IQueriable eg calling ToList() 仅当枚举IQueriable时才获取查询结果,例如,调用ToList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM