How to make lazy-loading work with EF Core 2.1.0 and proxies

岁酱吖の 提交于 2019-11-30 08:39:55

Steps To Configure Lazy Loading with Proxies in Asp.net Core 2.1

  1. Install Microsoft.EntityFrameworkCore.Proxies package
  2. Enable LazyLoadingProxies You can enable it with a call to UseLazyLoadingProxies:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(myConnectionString);

Or when using AddDbContext:

.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies()
      .UseSqlServer(myConnectionString));
  1. EF Core will then enable lazy loading for any navigation property that can be overridden--that is, it must be virtual.

You can try to configure proxies in Startup.cs like

public void ConfigureServices(IServiceCollection services)
{
    #region Database configuration

    // Database configuration
    services.AddDbContext<DbContext>(options =>
        options.UseLazyLoadingProxies()
            .UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));

    #endregion Database configuration
}

And by the way you can already update you app packages to pure 2.1.0 (not final or RC). One of the reasons why your configuration may not work is an unstable version of components.

NB: Microsoft.EntityFrameworkCore.Proxies.dll is installed from nuget independently from EFCore

I solved this by setting JSON serialization in service like this answer https://stackoverflow.com/a/49350457/4178475

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!