7

如果我有一个带有 BlogEntries 集合的博客实体,该集合可能有数百个条目,有没有办法首先使用 EF 代码添加任何服务器端分页功能?例如,如果我像在 DbSet 上那样执行典型的 .Skip(x).Take(y),它会延迟加载整个集合并将其分页到内存中吗?

4

1 回答 1

16

如果直接查询DbSet,可以使用 Take 和 Skip,它确实会在数据库服务器上执行分页(这些方法调用被转换为 SQL)。所以这可以按预期工作:

// Loads only 10 expected entries through Linq-to-entities
var entries = context.BlogEntries.OrderBy(e => e.Date).Skip(10).Take(10);

请注意,加载实体上的分页导航属性不能以这种方式工作:

var blog = context.Blogs.First();
// Lazy loading always loads all related entries and executes ordering and 
// paging through Linq-to-objects!
var entires = blog.BlogEntries.OrderBy(e => e.Date).Skip(10).Take(10);

如果要对导航属性进行分页,则必须使用显式加载

var blog = context.Blogs.First();
var dbEntry = context.Entry(blog);
// This is the way to use Linq-to-entities on navigation property and 
// load only subset of related entities
var entries = dbEntry.Collection(b => b.BlogEntries)
                     .Query()
                     .OrderBy(e => e.Date)
                     .Skip(10)
                     .Take(10)
                     .Load();
于 2012-04-30T07:23:30.180 回答