Paging in Entity Framework

前端 未结 6 1250
情书的邮戳
情书的邮戳 2020-12-03 00:56

In Entity Framework, using LINQ to Entities, database paging is usually done in following manner:

int totalRecords = EntityContext.Context.UserSet.Count;
var         


        
6条回答
  •  温柔的废话
    2020-12-03 01:37

    Suppose you want to get the details of Page 2 with a pagesize=4

    int page =2;
    int pagesize=4;
    
    var pagedDetails= Categories.Skip(pagesize*(page-1)).Take(pagesize)
    .Join(Categories.Select(item=>new {item.CategoryID,Total = Categories.Count()}),x=>x.CategoryID,y=>y.CategoryID,(x,y)=>new {Category = x,TotalRows=y.Total});
    

    The Output will have all details of Category and TotalRows.

    One DB call.

    Generated SQL

    -- Region Parameters
    DECLARE @p0 Int = 2
    DECLARE @p1 Int = 4
    -- EndRegion
    SELECT [t2].[CategoryID], [t2].[CategoryName], [t2].[Description], [t2].[Picture], [t5].[value] AS [TotalRows]
    FROM (
        SELECT [t1].[CategoryID], [t1].[CategoryName], [t1].[Description], [t1].[Picture], [t1].[ROW_NUMBER]
        FROM (
            SELECT ROW_NUMBER() OVER (ORDER BY [t0].[CategoryID], [t0].[CategoryName]) AS [ROW_NUMBER], [t0].[CategoryID], [t0].[CategoryName], [t0].[Description], [t0].[Picture]
            FROM [Categories] AS [t0]
            ) AS [t1]
        WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
        ) AS [t2]
    INNER JOIN (
        SELECT [t3].[CategoryID], (
            SELECT COUNT(*)
            FROM [Categories] AS [t4]
            ) AS [value]
        FROM [Categories] AS [t3]
        ) AS [t5] ON [t2].[CategoryID] = [t5].[CategoryID]
    ORDER BY [t2].[ROW_NUMBER]
    

提交回复
热议问题