跳过并采取:EF 4.1中OFFSET LIMIT的有效方法?

Tom*_*Tom 15 .net c# entity-framework

以下代码:

using (var db = new Entities())
{
    db.Blogs.First().Posts.Skip(10).Take(5).ToList();
}
Run Code Online (Sandbox Code Playgroud)

将生成以下SQL:

-- statement #1
SELECT TOP ( 1 ) [c].[Id] AS [Id],
             [c].[Title]          AS [Title],
             [c].[Subtitle]       AS [Subtitle],
             [c].[AllowsComments] AS [AllowsComments],
             [c].[CreatedAt]      AS [CreatedAt]
FROM [dbo].[Blogs] AS [c]

-- statement #2
SELECT [Extent1].[Id] AS [Id],
   [Extent1].[Title]    AS [Title],
   [Extent1].[Text]     AS [Text],
   [Extent1].[PostedAt] AS [PostedAt],
   [Extent1].[BlogId]   AS [BlogId],
   [Extent1].[UserId]   AS [UserId]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[BlogId] = 1 /* @EntityKeyValue1 */
Run Code Online (Sandbox Code Playgroud)

(来自http://ayende.com/blog/4351/nhibernate-vs-entity-framework-4-0)

NB Skip and Take尚未转换为SQL,导致博客中的所有帖子都从数据库加载,而不仅仅是我们要求的5.

这似乎很危险,非常低效.令人难以置信的是,是什么给出了什么?

Ben*_*thy 20

它发生的原因是调用First,这导致Blog对象被实现.任何进一步的遍历都需要更多查询.

请尝试db.Blogs.Take(1).SelectMany(b => b.Posts).Skip(10).Take(5).ToList();在一个查询中执行此操作.您可能希望在之前添加某种博客排序.Take(1),以确保确定性结果.

编辑 你实际上必须在Skip之前使用OrderBy(否则LINQ to Entities会抛出异常),这使它类似于:

db.Blogs.OrderBy(b => b.Id).Take(1) // Filter to a single blog (while remaining IQueryable)
    .SelectMany(b => b.Posts) // Select the blog's posts
    .OrderBy(p => p.PublishedDate).Skip(10).Take(5).ToList(); // Filter to the correct page of posts
Run Code Online (Sandbox Code Playgroud)