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

15,809

Solution 1

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.

Solution 2

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

Share:
15,809

Related videos on Youtube

KolesnichenkoDS
Author by

KolesnichenkoDS

Updated on March 29, 2020

Comments

  • KolesnichenkoDS
    KolesnichenkoDS about 4 years

    I have the following models:

    public class Session
    {
        public int SessionID { get; set; }
        public int UserID { get; set; }
    
        public virtual User User { get; set; }
    }
    
    public class User
    {
        public int UserID { get; set; }
        public int OrganizationID { get; set; }
    
        public virtual ICollection<Session> Sessions { get; set; }
        public virtual Organization Organization { get; set; }
    }
    
    public class Organization
    {
        public int OrganizationID { get; set; }
    
        public virtual ICollection<User> Users { get; set; }
    }
    

    that are registered in DbContext as:

    modelBuilder.Entity<Session>(entity =>
    {
        entity.ToTable("sessions");
    
        entity.Property(e => e.SessionID).HasColumnName("id");
        entity.Property(e => e.UserID).HasColumnName("user_id");
    
        entity.HasOne(e => e.User)
            .WithMany(e => e.Sessions)
            .HasForeignKey(e => e.UserID);
    }
    
    modelBuilder.Entity<User>(entity =>
    {
        entity.ToTable("users");
    
        entity.Property(e => e.UserID).HasColumnName("id");
        entity.Property(e => e.OrganizationID).HasColumnName("organization_id");
    
        entity.HasOne(e => e.Organization)
            .WithMany(e => e.Users)
            .HasForeignKey(e => e.OrganizationID);
    }
    
    modelBuilder.Entity<Organization>(entity =>
    {
        entity.ToTable("organizations");
    
        entity.Property(e => e.OrganizationID).HasColumnName("id");
    }
    

    I'm trying to use lazy loading with Microsoft.EntityFrameworkCore.Proxies as described here:

    builder.Register(c =>
    {
        var optionsBuilder = new DbContextOptionsBuilder<Context>();
        optionsBuilder
            .UseLazyLoadingProxies()
            /* more options */
            ;
    
        var opts = optionsBuilder.Options;
    
        return new Context(opts);
    }).As<DbContext>().InstancePerLifetimeScope();
    

    I'm querying sessions using context.All<Session>. However, Session.User and Session.User.Organization are null by default. To load them I have to do something like context.All<Session>().Include(s => s.User).Include(s => s.User.Organization). How can I avoid that? Why doesn't UseLazyLoadingProxies work?


    • .NET Core version: 2.1.300-preview2-008533
    • Target: netcoreapp2.1
    • EF Core (and Proxies) version: 2.1.0-preview2-final
    • Opi
      Opi almost 6 years
      Did you happen to find a solution? Having the same issue
    • Krzysztof Skowronek
      Krzysztof Skowronek almost 6 years
      To be honest, do you really need lazy-loading? I tried that with full EF and found it not very usefull, since it only works as long as you have your context alive,so if you want to just fetch all information, you still have to manually load all properties or keep the context alive. I created extension methods for DbSets like BuildSession, BuldUser that contain all includes I need.