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

编程入门 行业动态 更新时间:2024-10-26 09:18:15
本文介绍了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<MyLazyContext>传递给需要DbContextOptions<MyContext>的基本构造函数时遇到问题,因此我将它们都更改为DbContextOptions<MyContext>.当此方法在我的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:36:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   加载   EF   Core

发布评论

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

>www.elefans.com

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