EF Core 延迟加载

EF Core 默认不支持 延迟加载 Lazy Loading(延迟加载的优点:减少交互数据量(不能减少交互次数)); 按需加载数据
默认不支持的原因:延迟加载有滥用的现象

实现方式 ==>

  1. 使用开源组件 ** Z.EntityFramework.Plus.EFCore**
    需要进行延迟加载的字段标注 virtual

  2. 使用微软组件 Microsoft.EntityFrameworkCore.Abstractions

    使用ILazyLoader接口

       public class Blog
        {
            private ILazyLoader LazyLoader { get; set; }
    
            public Blog(ILazyLoader lazyLoader)
            {
                LazyLoader = lazyLoader;
            }
            public int Id { get; set; }
            public string Name { get; set; }
            public string Url { get; set; }
            public DateTime CreatedTime { get; set; }
            public DateTime ModifiedTime { get; set; }
            public byte Status { get; set; }
            public bool IsDeleted { get; set; }
    
            private ICollection<Post> _posts;
    
            public ICollection<Post> Posts
            {
                get => LazyLoader?.Load(this, ref _posts);
                set => _posts = value;
            }
        }
    

延迟加载避免循环引用

循环引用 => *由于数据库主外键关联,将对象进行Json序列化时会遇到循环引用的问题*

若在.NET Core Web应用程序中启用了延迟加载,为了避免虚循环引用问题,需要在ConfigureServices方法中进行如下配置

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc().AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
}
原文地址:https://www.cnblogs.com/louiszh/p/14768540.html