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

时间:2014-04-23 13:22:34

标签: 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语句执行查询?

1 个答案:

答案 0 :(得分: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)
...

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

相关问题