在Linq2SQL中使用分页的TotalRowCount

时间:2011-06-08 18:36:19

标签: c# linq performance linq-to-sql paging

我从相当复杂的linq查询中获取分页数据源。我的问题是需要两倍的执行时间,因为我需要在应用分页之前获得总行数以计算nr。页面显示。 (查询将执行两次)

我能以某种方式以更优化的方式做到这一点吗?就像在某种程度上使用SQL的@@ rowcount一样?

这大致就是现在的查询。 (使用Dynamic linq)

    public IList<User> GetPagedUsers(string filter, string sort, int skip, 
       int take, out int totalRows)
    {
            using(var dbContext = new DataContext())
            {
               IQueryable<User> q = GetVeryComplexQuery(dbContext);

               //Apply filter if exists
               if (!string.IsNullOrEmpty(filter))
                   q = q.Where(filter);

               //Set total rows to the out parameter
               totalRows = q.Count(); //Takes 4 sec to run

               //Apply sort if exists
               if (!string.IsNullOrEmpty(sort))
                   q = q.OrderBy(sort);

               //Apply paging and return
               return q.Skip(skip).Take(take).ToList(); //Takes 4 sec to run
            }
    }

为什么不这样做呢?

TblCompanies.Dump(); //150 rows
ExecuteQuery<int>("select @@ROWCOUNT").Dump(); //returns 0

1 个答案:

答案 0 :(得分:3)

Linq2Sql实际上将翻译使用Skip&amp;进入SQL语句,即使你可以获得@@ RowCount,该值也不会比你的参数更好。

如果我们采用以下简单示例(取自MSDN http://msdn.microsoft.com/en-us/library/bb386988.aspx)。

IQueryable<Customer> custQuery3 =
    (from custs in db.Customers
     where custs.City == "London"
     orderby custs.CustomerID
     select custs)
    .Skip(1).Take(1);

foreach (var custObj in custQuery3)
{
    Console.WriteLine(custObj.CustomerID);
}

生成以下SQL

SELECT TOP 1 [t0].[CustomerID], [t0].[CompanyName],
FROM [Customers] AS [t0]
WHERE (NOT (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM (
        SELECT TOP 1 [t1].[CustomerID]
        FROM [Customers] AS [t1]
        WHERE [t1].[City] = @p0
        ORDER BY [t1].[CustomerID]
        ) AS [t2]
    WHERE [t0].[CustomerID] = [t2].[CustomerID]
    ))) AND ([t0].[City] = @p1)
ORDER BY [t0].[CustomerID]

因此,您可以看到跳过实际发生在SQL语句中,因此@@ RowCount将等于查询返回的行数而不是整个结果集。