Entity Framework core .Include() issue

后端 未结 4 1073
长发绾君心
长发绾君心 2021-02-18 22:05

Been having a play about with ef core and been having an issue with the include statement. For this code I get 2 companies which is what i expected.



        
4条回答
  •  有刺的猬
    2021-02-18 23:02

    I know this is an old issue, but its the top result in google, so im putting my solution i I found here. For a Core 3.1 web project there is a quick fix. Add nuget package Microsoft.EntityFrameworkCore.Proxies. Then you simply just need to specify in your options builder when configuring your services. Docs: https://docs.microsoft.com/en-us/ef/core/querying/related-data

    public void ConfigureServices(IServiceCollection services) {    
        services.AddDbContextPool(options => {
            options.UseLazyLoadingProxies();
            options.UseSqlServer(this.Configuration.GetConnectionString("MyCon"));
        });
    }
    

    Now your lazy loading should work as it did in previous EF versions. If you not using it for a web project, you can do it right inside of the OnConfiguringMethod inside of your DbContext itself.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        optionsBuilder.UseLazyLoadingProxies();
    }
    

    My EF stuff is kept in a separate class library so i can re-use it through multiple company applications. So having the ability to not lazy load when not needed for a particular application is useful. So i prefer passing in the build options, for reuse-ability purposes. But both will work.

提交回复
热议问题