PagedList在asp.net mvc

时间:2015-10-09 11:31:07

标签: c# sql-server asp.net-mvc entity-framework pagedlist

在我的项目中,我需要对查询进行分页。我使用实体框架从数据库中获取数据。 This video on youtube解释了如何对查询进行分页。简而言之,视频说你所要做的就是将PagedList.Mvc安装到你的项目和这段代码

.ToPagedList(PageNumber,PageSize)

第一时间,似乎这项工作对我来说很有用,但我发现(在使用Sql server profile检查哪些实体框架传递给sql server之后)实体框架请求sql server获取所有数据然后选择所需的数据。更清楚一点,这是我在c#(服务器端)上的代码

var messages = db.Messages.Where(x => x.User1 == 1 && x.User2 == 2).OrderBy(x=>x.Date).ToList().ToPagedList(1,4);

传递给sql server的是:

exec sp_executesql N'SELECT 
    [Project1].[Id] AS [Id], 
    [Project1].[User1] AS [User1], 
    [Project1].[User2] AS [User2], 
    [Project1].[Direction] AS [Direction], 
    [Project1].[TextContent] AS [TextContent], 
    [Project1].[ReadBit] AS [ReadBit], 
    [Project1].[Date] AS [Date], 
    [Project1].[ReceivedBit] AS [ReceivedBit]
    FROM ( SELECT 
        [Extent1].[Id] AS [Id], 
        [Extent1].[User1] AS [User1], 
        [Extent1].[User2] AS [User2], 
        [Extent1].[Direction] AS [Direction], 
        [Extent1].[TextContent] AS [TextContent], 
        [Extent1].[ReadBit] AS [ReadBit], 
        [Extent1].[ReceivedBit] AS [ReceivedBit], 
        [Extent1].[Date] AS [Date]
        FROM [Messages].[Messages] AS [Extent1]
        WHERE ([Extent1].[User1] = @p__linq__0) AND ([Extent1].[User2] = @p__linq__1)
    )  AS [Project1]
    ORDER BY [Project1].[Date] ASC',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=1,@p__linq__1=2

所以在sql server中没有分页,我认为这样的分页没有优势。我是否会错过一些无法正常工作的内容?或者是这样的工作?

1 个答案:

答案 0 :(得分:5)

PagedListSkip()Take()附加到您的查询中(计算要从PageNumberPageSize跳过的行数)。但是查询应该是原始IQueryable,以便这些添加到达查询提供程序并影响SQL转换。 ToList打破了这种联系。