entity-framework - 在 Entity Framework 代码中,有没有办法向导航集合添加分页?

标签 entity-framework collections ef-code-first paging

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

最佳答案

如果直接查询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();

关于entity-framework - 在 Entity Framework 代码中,有没有办法向导航集合添加分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378375/

相关文章:

c# - Entity Framework - ToList() 和 0 条记录

c# - 如何验证集合是否包含所有唯一对象

entity-framework - Entity Framework 并发 token 日期时间类型的问题

ef-code-first - EntityFramework Core 生产迁移

c# - Entity Framework 复杂的树结构

c# - 与 ILMerge 合并后找不到 Entity Framework

c# - 使用 --configuration 运行的 dotnet ef 导致 MSB4006

java - 让 Java 集合二分搜索返回多个值

powershell - 索引到 PowerShell 值集合

entity-framework - 使用linq获取模型类Entity Framework Code First的NotMapped属性中的值