c# - DbSet<T>.Where(where).ToList() - 为什么 SQL 不包含 where 子句?

标签 c# entity-framework entity-framework-6

为什么 EF 6 使用以下代码查询数据库中的所有记录?

    public virtual List<T> Find(Func<T, bool> where = null)
    {
        _db.Configuration.LazyLoadingEnabled = false;
        if (where == null) throw new NullReferenceException("The 'where' parameter of the Repository.Find() method is null.");    
        return _dbSet.Where(where).ToList();
    }

产生以下输出

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Sequence] AS [Sequence],
    [Extent1].[Description] AS [Description],
    [Extent1].[Instructions] AS [Instructions],
    [Extent1].[WorkCenterOperationId] AS [WorkCenterOperationId],
    [Extent1].[JobId] AS [JobId],
    [Extent1].[JobAssemblyId] AS [JobAssemblyId],
    [Extent1].[RowVersion] AS [RowVersion]
    FROM [dbo].[JobOperations] AS [Extent1]

两个问题:

  1. 为什么不使用 where 语句执行查询?
  2. 如何使用 where 语句获取要执行的查询?

最佳答案

您使用了 Func<T,bool>而不是 Expression<Func<T,bool>>因此,您已经(在某处)强制从数据库 Linq-to-Entities 过渡到 Linq-to-Objects。所以它是在内存中处理的。


而且,正如@Marc 指出的那样,一个简单的解决方法可能是:

public virtual List<T> Find(Expression<Func<T, bool>> where = null)
...

但这又取决于调用代码的形式是否可以生成 Func<T,bool>Expression<Func<T,bool>> (通常,lambda 可以转换为任何一种形式)

关于c# - DbSet<T>.Where(where).ToList() - 为什么 SQL 不包含 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23245706/

相关文章:

c# - EF 6.2 的多个复合索引

c# - 使用逗号分隔符拆分字符串,但如果它是使用 C# 的货币值则不拆分

c# - Visual Studio 2017 - 消息筛选器指示应用程序正忙

c# - 我可以在 EF 中以良好的方式获取列表吗

c# - 如何撤消对 self 跟踪实体所做的所有更改?

asp.net-web-api - 到 Web Api 的动态连接字符串

entity-framework-6 - 启用迁移不适用于具有现有数据库配置的项目

c# - 有没有一种干净的方法可以将 C# 'params object[]' 构造函数参数转换为 C++ 构造函数?

c# - Selenium 网络驱动程序 : select value from KendoUI DropDownList

c# - 如何清除 Entity Framework 中的跟踪实体