[英]Generic EF6 Repository Method Doesn't Generate Correct SQL
I have this method in my repository exposing EF6 DbContext. 我的存储库中有此方法,用于公开EF6 DbContext。
public IList<T> GetEntities<T>(Func<T, bool> predicate) where T : class
{
return db.Set<T>().Where(predicate).ToList<T>();
}
When I watch this method execute in SQL Profiler, the predicate is executed in memory. 当我看到此方法在SQL Profiler中执行时,谓词在内存中执行。 The SQL statement contains no where clause. SQL语句不包含where子句。
Any ideas? 有任何想法吗?
.Where
accepts one of two things, either Func<T, bool>
or Expression<Func<T, bool>>
. .Where
接受两种情况之一,要么Func<T, bool>
或Expression<Func<T, bool>>
。 If you pass in Expression<Func<T, bool>>
, then your EF query should work properly. 如果您传递Expression<Func<T, bool>>
,那么您的EF查询应该可以正常工作。
public IList<T> GetEntities<T>(Expression<Func<T, bool>> predicate) where T : class
You'd call it the same way: 您可以用相同的方式称呼它:
GetEntities(x => x.Id == 34)
When you pass in Func<T, bool>
, the IEnumerable<T>
implementation executes, which uses Linq-to-Objects rather than Linq-to-Entities. 传递Func<T, bool>
,将执行IEnumerable<T>
实现,该实现使用Linq-to-Objects而不是Linq-to-Entities。
Your predicate should be an Expression
so that Entity Framework can actually use it to generate SQL instead of just executing it. 您的谓词应该是一个Expression
以便实体框架可以实际使用它来生成SQL,而不仅仅是执行它。 If you pass in a Func
you are actually calling the Enumerable.Where
method instead of Queryable.Where
: 如果传入Func
,则实际上是在调用Enumerable.Where
方法而不是Queryable.Where
:
public IList<T> GetEntities<T>(Expression<Func<T, bool>> predicate) where T : class
{
return db.Set<T>().Where(predicate).ToList<T>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.