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

Pri*_*nes 4 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();
    }
Run Code Online (Sandbox Code Playgroud)

产生以下输出

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]
Run Code Online (Sandbox Code Playgroud)

两个问题:

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

Dam*_*ver 8

你使用的是一个Func<T,bool>而不是一个Expression<Func<T,bool>>,所以你强迫(某处)从数据库Linq-Entities到Linq-to-Objects的转换.所以它在内存中处理.


并且,正如@Marc所指出的,一个简单的修复可能是:

public virtual List<T> Find(Expression<Func<T, bool>> where = null)
...
Run Code Online (Sandbox Code Playgroud)

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