获取COUNT时Linq Select语句速度较慢

本文关键字:速度 语句 Select COUNT Linq 获取 | 更新日期: 2023-09-27 17:59:26

我正试图使用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();
   }        
}

获取COUNT时Linq Select语句速度较慢

您可以显著简化查询:

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时,它将发出查询,并且服务器将只返回一个数字,而不是一个表。

这对性能来说并不重要,但我认为如果没有那么多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);
}

您可以极大地简化事情,只需使用计数扩展方法

你试过吗:

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

删除调用.ToList()。它强制查询将整个结果拉到客户端。

通过删除这一点,只需直接对tr的结果调用.Count()(没有ToList()),Count()就成为查询本身的一部分,并远程执行,这将极大地简化这一过程:

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);
        // This can be added above, or left here - the end result is the same
        return tr.Count();
    }        
}