我正在寻找一种可能的方法来在我的 DbContext 中启用延迟加载,但并非总是如此,仅在我需要它的特定情况下.由于像 N+1 查询大数据集和 JSON 序列化遍历对象属性和序列化我的整个数据库等问题,我通常不想要延迟加载.但是,在某些情况下,我确实想要它.生成报告时,我加载一个顶级对象和许多子对象以填充报告字段.由于架构的性质,这将需要 30 个或更多 Include() 和 ThenInclude() 调用而无需延迟加载.
I am looking for a possible way to enable Lazy Loading in my DbContext but not all the time, only in specific instances when I need it. Because of issues like the N+1 queries with large datasets and JSON serialization traversing object properties and serializing my entire database I usually do not want Lazy Loading. However, in some instances I do want it. When generating reports I load a top-level object and many child objects in order to populate the report fields. Due to the nature of the schema this would need 30 or more Include() and ThenInclude() calls without Lazy Loading.
有没有办法在查询时有条件地启用延迟加载?我尝试使用 2 个 DbContexts,一个扩展另一个并启用延迟加载,如下所示:
Is there a way to enable Lazy Loading conditionally when doing a query? I tried using 2 DbContexts, with one extending the other and enabling Lazy Loading, like this:
public class MyLazyContext : MyContext { public MyLazyContext(DbContextOptions<MyLazyContext> options) : base(options) { } protected override OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseLazyLoadingProxies(); } }并将它们作为依赖项单独注入.构造函数在将 DbContextOptions 传递给需要 DbContextOptions 的基本构造函数时遇到问题,所以我将它们都更改为 DbContextOptions>.虽然这在我的 Web 应用程序中有效,但由于我的通用类激活器如何为 DbContext 工作,我的单元测试被破坏了 - 这让我认为这种方法是代码异味,所以我开始寻找更好的解决方案.
And injecting them separately as dependencies. The constructor had a problem with passing DbContextOptions<MyLazyContext> to the base constructor requiring DbContextOptions<MyContext> so I changed them both to DbContextOptions<MyContext>. While this worked in my web application, my unit tests were broken due to how my generic class activators worked for DbContext - this got me thinking that this approach was code smell so I started looking for a better solution.
推荐答案您可以使用 ChangeTracker.LazyLoadingEnabled 属性:
You can use ChangeTracker.LazyLoadingEnabled property:
获取或设置一个值,该值指示是否将在首次访问时加载被跟踪实体的导航属性.
Gets or sets a value indicating whether navigation properties for tracked entities will be loaded on first access.
默认值为 true.
例如
context.ChangeTracker.LazyLoadingEnabled = false; var query = context.Set<…>()...;更多推荐
EF Core 有条件地启用延迟加载
发布评论