【问题标题】:Entity Framework Linq query not generating where clause in SQL Server when passed as a predicate当作为谓词传递时,实体框架 Linq 查询不会在 SQL Server 中生成 where 子句
【发布时间】:2021-04-09 04:03:26
【问题描述】:

我在 .NET Core 3.1 中创建了一个全新的项目,我正在创建的查询正在生成一个不包含 where 子句而是读取整个表的 SQL 查询(在 SQL Server Profiler 中查看)。有没有办法传入谓词并将其合并到最终生成的 SQL 语句中?

在下面的函数中,query1IQueryable<Balance>query2IEnumerable<Balance>

    public int GetCount(Func<Balance, bool> predicate)
    {
        var query1 = (from b in _appContext.Balance
                      select b
                      );
        var query2 = query1.Where(predicate);
        var count = query2.Count();

        return count;
    }

这样称呼:

    GetCount(p => p.Email == 'test@gmail.com');

【问题讨论】:

  • 好的...我发现这个答案令人困惑...但它确实有一个链接可以帮助我。
  • 您使用的是什么 LINQ(您的标签有冲突):LINQ to SQL / EF 6.x / EF Core 2.0 / 2.1 / 3.x / 5.x?我猜 LINQ to EF Core 2.x 在无法使用服务器端时会自动转换为客户端处理。
  • @NetMage 老实说,我不知道...我如何确定这个?

标签: sql-server .net-core linq-to-sql entity-framework-core


【解决方案1】:

这个答案帮助了我:Create Expression from Func

基本上我必须将 Func 包装在一个表达式中,如下所示:

    public int GetCount(Expression<Func<Balance, bool>> predicate)
    {
        return = (from b in _appContext.TableName
                  select b
                  ).Where(predicate).Count();
    }

同样的调用奏效了:

    GetCount(p => p.Email == 'test@gmail.com');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多