gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:31:44 25 4
gpt4 key购买 nike

为什么 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com