如何查询有序实体集中的每个第n个值?

时间:2010-06-22 13:43:39

标签: linq-to-entities

我想为每第n行查询一个EF 4实体集,这样我得到的结果不会超过x。例如,给定一组1000个名字,给我每100个名字(按名称排序),这样我就有10个结果。

LINQ to Entities能以任何有效的方式实现这种事吗?

1 个答案:

答案 0 :(得分:1)

不在L2S中,但您可以使用ExecuteStoreQuery执行此操作:

你想要SQL:

SELECT 
[Project1].[C1] AS [C1], 
[Project1].[DepartmentId] AS [DepartmentId], 
[Project1].[Code] AS [Code], 
[Project1].[DepartmentName] AS [DepartmentName]
FROM ( SELECT [Project1].[DepartmentId] AS [DepartmentId], [Project1].[Code] AS [Code], [Project1].[DepartmentName] AS [DepartmentName], [Project1].[C1] AS [C1], row_number() OVER (ORDER BY [Project1].[DepartmentName] ASC) AS [row_number]
    FROM ( SELECT 
        [Extent1].[DepartmentId] AS [DepartmentId], 
        [Extent1].[Code] AS [Code], 
        [Extent1].[DepartmentName] AS [DepartmentName]
        1 AS [C1]
        FROM [dbo].[Department] AS [Extent1]
    )  AS [Project1]
)  AS [Project1]
WHERE [Project1].[row_number] % 4 = 0          
ORDER BY [Project1].[DepartmentName] ASC

(或者用param代替我的硬编码4。)

然后代码如下:

var q = Context.ExecuteStoreQuery<Foo>(
    sql, params);