我在 EF CodeFirst 中使用Take
andSkip
语句来实现分页(正如Zoran Maksimovic在这篇文章中所说),这些语句导致 EF 生成这样的 sql 查询(我的页面大小为 100):
SELECT TOP (100) [Filter1].[Id] AS [Id],
[Filter1].[SendDuration] AS [SendDuration]
FROM (SELECT [Extent1].[Id] AS [Id],
[Extent1].[SendDuration] AS [SendDuration],
row_number() OVER (ORDER BY [Extent1].[SendDuration] DESC) AS [row_number]
FROM [dbo].[MyView] AS [Extent1]
WHERE (1293>= [Extent1].[Id])
)AS [Filter1]
WHERE [Filter1].[row_number] > 500
ORDER BY [Filter1].[SendDuration] DESC
但是当在 sql server 中运行时,这个 sql 太慢了,但是正如Boanerge在他的评论中所说,使用row_number < X
而不是Top(y)
导致性能提高。我的意思是,如果我将生成的 sql 更改为:
SELECT [Filter1].[Id] AS [Id],
[Filter1].[SendDuration] AS [SendDuration]
FROM (SELECT [Extent1].[Id] AS [Id],
[Extent1].[SendDuration] AS [SendDuration],
row_number() OVER (ORDER BY [Extent1].[SendDuration] DESC) AS [row_number]
FROM [dbo].[MyView] AS [Extent1]
WHERE (1293>= [Extent1].[Id])
)AS [Filter1]
WHERE [Filter1].[row_number] > 500 and [Filter1].[row_number] <= 600
ORDER BY [Filter1].[SendDuration] DESC
查询执行时间会更好,更容易接受(在某些情况下快 4 或 5 倍)。有什么方法可以强制 EF 生成第二个 Sql 而不是第一个 Sql?