c# - 获取 COUNT 时 Linq Select 语句变慢

标签 c# asp.net linq entity-framework linq-to-entities

我正在尝试使用 EntityFramework 和 Linq 从以下方法中获取总记录数。返回计数很慢。

public static int totalTracking(int id)
{
   using (var ctx = new GPEntities())
   {
      var tr = ctx.Tracking
                   .Where(c => c.clientID == Config.ClientID)
                   .Where(c => c.custID == id)
                   .Where(c => c.oOrderNum.HasValue)
                  .ToList();
      return tr.Count();
   }        
}

最佳答案

您可以显着简化查询:

using (var ctx = new GPEntities())
{
    return ctx.Tracking
        .Where(c => c.clientID == Config.ClientID)
        .Where(c => c.custID == id)
        .Where(c => c.oOrderNum.HasValue)
        .Count();
}

当您调用 ToList 时,这将触发具体化,因此将向数据库发出查询并检索所有列。实际计数将发生在客户端。

如果您只执行 Count,而没有 ToList,当您调用 Count 时,它会发出查询,服务器将只返回一个数字,而不是一张 table 。

这对性能来说并不是那么关键,但我认为如果没有那么多 Where,代码看起来会更漂亮一些:

using (var ctx = new GPEntities())
{
    return ctx.Tracking
        .Where(c => 
            c.clientID == Config.ClientID &&
            c.custID == id &&
            c.oOrderNum.HasValue)
        .Count();
}

甚至

using (var ctx = new GPEntities())
{
    return ctx.Tracking
        .Count(c => 
            c.clientID == Config.ClientID &&
            c.custID == id &&
            c.oOrderNum.HasValue);
}

关于c# - 获取 COUNT 时 Linq Select 语句变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379996/

相关文章:

C# 将函数作为参数传递

javascript - 如何根据我的以下要求处理Javascript的Confirm()?

asp.net - 切换 asp.net 连接字符串 live/test/dev

c# - 如何在 C# 中根据 ID 向嵌套列表中填充数据?

c# - VS2015 即时窗口中的 lambda 表达式

c# - Excel 工作簿导入错误

c# - 将一个按钮绑定(bind)到 3 个不同的 DataGrids,每个 DataGrids 在 TabControl 中

c# - 如何确定 Facebook 用户是否登录到 Facebook 从 C# 连接

javascript - 使用 ASP.Net Razor Pages 进行条件验证

c# - Linq-to-SQL 连接 where 子句中的两列