c# - 通用 EF6 存储库方法不会生成正确的 SQL

标签 c# sql-server entity-framework

我的存储库中有此方法公开 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子句。

有什么想法吗?

最佳答案

.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。

关于c# - 通用 EF6 存储库方法不会生成正确的 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38857007/

相关文章:

c# - ASP.NET Core - 如何在另一个 Controller 中重用在一个 Controller 中创建的方法?

c# - 如何使用 NLog 跟踪每个请求 ASP.NET Web API

sql-server - 我可以在事务期间在单独的事务中运行一些SQL吗

c# - 忽略上下文更新中的空值

c# - 表达式... LINQ to Entities 仅支持转换实体数据模型原始类型”

c# - 在 C# 中将 LDAP AccountExpires 转换为 DateTime

c# - 指向 C# 中非托管代码的函数的指针

c++ - SQL numeric(18,0) 数据类型对应的 C++ 数据类型是什么?

c# - Entity Framework - 具有多对多表的用户和组

.net - EF Code First 4.3 命名约定外键