实体框架分页查询翻译性能改进

时间:2014-04-30 10:44:10

标签: c# sql linq entity-framework

EF将Linq查询转换为返回的分页结果的方式如下所示

Linq查询:context.Student.OrderBy(x => x.Id).Skip(10).Take(10).ToList()

EF将其翻译为:SELECT TOP (10) [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name] FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number] FROM [dbo].[Students] AS [Extent1] ) AS [Extent1] WHERE [Extent1].[row_number] > 10 ORDER BY [Extent1].[Id] ASC

对于百万分之一记录到初始页面的数据库,它需要大约2秒,但对于最后一页,例如对于页码999999,所有索引都需要7秒以上。

但是当我改变这个翻译的查询时,

SELECT TOP (10) 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name]
FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name]
, FLOOR(row_number() OVER (ORDER BY [Extent1].[Id] ASC) /10 ) AS [page_number]
    FROM [dbo].[Students] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[page_number] = 10
ORDER BY [Extent1].[Id] ASC

我使用Floor函数将row_number转换为page_number并使用了相等的运算符然后我可以在大约2秒内加载页码999999,其中初始页面少于1秒。

我想知道有没有办法像我使用的那样使用page_number函数FLOOR(row_number() OVER (ORDER BY [Extent1].[Id] ASC) /10 )并传递页码来加载分页记录。

避免> symbol和using =运算符对select语句的性能有很大的影响。

0 个答案:

没有答案