Skip and Take in Entity Framework Core

落爺英雄遲暮 提交于 2019-12-12 12:08:31

问题


I have simple POCO classes:

public class Library
{
    [Key]
    public string LibraryId { get; set; }

    public string Name { get; set; }

    public List<Book> Books { get; set; }
}

public class Book
{
    [Key]
    public string BookId { get; set; }

    public string Name { get; set; }

    public string Text { get; set; }
}

And I have query, that returns libraries with already included books:

dbContext.Set<Library>.Include(x => x.Books);

I'm trying to skip 5 libraries and then take 10 of them:

await dbContext.Set<Library>.Include(x => x.Books).Skip(5).Take(10).ToListAsync();

The problem is, that when I'm trying to perform Skip and Take methods on this query, it returns libraries without included list of books.

How can I work with Skip and Take, with saving previously included entities?


回答1:


Usually you need to Order By first before use Skip and Take methods. Try ordering by name like this way:

await dbContext.Set<Library>().Include(x => x.Books)
                              .OrderBy(x=>x.Name)
                              .Skip(5)
                              .Take(10)
                              .ToListAsync();

As far as I remember your query should be translated using OFFSET-FETCH filter which requires an ORDER BY clause to exist.



来源:https://stackoverflow.com/questions/37683555/skip-and-take-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!