What is the equivalent of .Configuration.ProxyCreationEnabled in EF Core?

前端 未结 1 1775
無奈伤痛
無奈伤痛 2021-01-13 19:52

What is the equivalent of .Configuration in Entity Framework Core? Receiving error below

Code Examples:

        List

        
相关标签:
1条回答
  • 2021-01-13 20:31

    Based on Entity Framework Core docs: https://docs.microsoft.com/en-us/ef/core/querying/related-data, from EF Core 2.1, there is a way to enable Lazy Loading with or without proxy.

    1. Lazy Loading with Proxy:

    a. Make sure your navigation property are defined as "virtual"

    b. Install the Microsoft.EntityFrameworkCore.Proxies package

    c. Enable it with a call to UseLazyLoadingProxies

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer(myConnectionString);
    

    Or enable it when using AddDbContext

    .AddDbContext<BloggingContext>(
        b => b.UseLazyLoadingProxies()
              .UseSqlServer(myConnectionString));
    

    2. Lazy Loading without Proxy:

    a. Injecting the ILazyLoader service into an entity, as described in Entity Type Constructors. For example:

    public class Blog
    {
        private ICollection<Post> _posts;
    
        public Blog()
        {
        }
    
        private Blog(ILazyLoader lazyLoader)
        {
            LazyLoader = lazyLoader;
        }
    
        private ILazyLoader LazyLoader { get; set; }
    
        public int Id { get; set; }
        public string Name { get; set; }
    
        public ICollection<Post> Posts
        {
            get => LazyLoader.Load(this, ref _posts);
            set => _posts = value;
        }
    }
    

    By default, EF Core won't use lazy load with proxy, but if you want to use proxy, please follow 1st approach.

    0 讨论(0)
提交回复
热议问题