通用的EF6存储库方法不能生成正确的SQL

本文关键字:SQL 不能 方法 EF6 存储 | 更新日期: 2023-09-27 18:01:47

我有这个方法在我的存储库暴露EF6 DbContext。

public IList<T> GetEntities<T>(Func<T, bool> predicate) where T : class
{
    return db.Set<T>().Where(predicate).ToList<T>();
}

当我观察这个方法在SQL Profiler中执行时,谓词是在内存中执行的。SQL语句不包含where子句。

任何想法?

通用的EF6存储库方法不能生成正确的SQL

.Where接受两个事物中的一个,Func<T, bool>Expression<Func<T, bool>>。如果您通过Expression<Func<T, bool>>,那么您的EF查询应该正常工作。

public IList<T> GetEntities<T>(Expression<Func<T, bool>> predicate) where T : class

你也可以这样称呼它:

GetEntities(x => x.Id == 34)

当您传入Func<T, bool>时,执行IEnumerable<T>实现,它使用Linq-to-Objects而不是Linq-to-Entities。

您的谓词应该是Expression,以便实体框架实际上可以使用它来生成SQL,而不仅仅是执行它。如果你传入一个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>();
}