EF Core 有条件地启用延迟加载

编程入门 行业动态 更新时间:2024-10-26 07:27:50
本文介绍了EF Core 有条件地启用延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种可能的方法来在我的 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 有条件地启用延迟加载

本文发布于:2023-11-14 10:35:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   加载   EF   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!