获取COUNT时,Linq Select Statement变慢

Rav*_*Ram 6 c# linq asp.net linq-to-entities entity-framework

我试图从使用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();
   }        
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*Aza 10

您可以显着简化查询:

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();
}
Run Code Online (Sandbox Code Playgroud)

当您调用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();
}
Run Code Online (Sandbox Code Playgroud)

甚至

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