EF Core启用有条件的延迟加载 [英] EF Core enable Lazy Loading conditionally

查看:532
本文介绍了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.

推荐答案

您可以使用

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启用有条件的延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆