我执行使用实体框架的服务器端分页,并有下面的代码LINQ到实体排序依据评估时的KeySelectors传递
DbQuery<T> query = Context.Set<T>();
query = IncludeNavigationProperties(query, includedProperties);
var result = query.OrderBy(arg => arg.DatabaseId)
.Skip((pageNumber - 1)*pageSize)
.Take(pageSize).ToList();
产生我仅查询所需数据的SQL(使用SQL查询检查早Server事件探查器)
SELECT TOP (21)
[Extent1].[DatabaseId] AS [DatabaseId],
...[other props here]...
FROM (SELECT [Extent1].[DatabaseId] AS [DatabaseId], ...[other props here]..., row_number() OVER (ORDER BY [Extent1].[DatabaseId] ASC) AS [row_number]
FROM [dbo].[Table] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 84
ORDER BY [Extent1].[DatabaseId] ASC
于是我决定重新使用更多的情况下,这方法并传递keySelector
作为一个外部变量:
DbQuery<T> query = Context.Set<T>();
query = IncludeNavigationProperties(query, includedProperties);
var result = query.OrderBy(keySelector)
.Skip((pageNumber - 1)*pageSize)
.Take(pageSize).ToList();
其中
Func<T, int> keySelector = arg => arg.DatabaseId;
但它突然产生下面的SQL查询:
SELECT
[Extent1].[DatabaseId] AS [DatabaseId],
...[other props here]...
FROM [dbo].[Table] AS [Extent1]
其中,据我了解,查询表所有数据,然后对其进行处理的服务器。
所以,我有2个问题:
- 为什么查询变化?
- 我该如何修复它(能够改变
keySelector
并只查询必要的数据)?