Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core - How enable lazy loading in Entity framework core?

I've separated the Read Context from Write Now I'm going to enable LazyLoading in ReadOnlyContext by default. I also used the following method, but unfortunately it does not work.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseLazyLoadingProxies()
        .UseSqlServer(@"Data Source=.;Initial Catalog=UniversityDb;Persist Security Info=True;User ID=admin;Password=asdasdsadasd");
}

my model:

public class Partner : BaseEntity<int>
{
    public string Name { get; set; }
    public DateTime CreateDate { get; set; }
    public bool IsDisabled { get; set; }
    public bool IsDeleted { get; set; }
    public virtual ICollection<PartnerUser> PartnerUsers { get; set; }
}

my ef version:

EntityFramework core v 2.1.2

public async Task<PartnerQuery> Get(int id)
{
    var result = await _partnerDbSet.SingleAsync(c => c.Id == id);
    var list = result.PartnerUsers;
    return new PartnerQuery()
    {
        CreateDate = result.CreateDate,
        Name = result.Name,
        Id = result.Id
    };
}

I got this error:

"Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning: An attempt was made to lazy-load navigation property 'PartnerUsers' on detached entity of type 'PartnerProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'.'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'."

How can this problem be solved?

like image 341
John Avatar asked Sep 24 '18 08:09

John


People also ask

How do I enable lazy loading in Entity Framework?

Lazy loading with proxiesUseLazyLoadingProxies() . UseSqlServer(myConnectionString)); EF Core will then enable lazy loading for any navigation property that can be overridden--that is, it must be virtual and on a class that can be inherited from. For example, in the following entities, the Post.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

Does EF core use lazy loading by default?

Lazy Loading is the default behavior of LINQ that's why it is the default behavior of EF Core. With lazy loading, all related entities are not loaded along with the parent entity automatically.

Which entities allow lazy loading?

Yes, lazy loading is enabled in the Entity Framework ORM too, it is on by default in Entity Framework, so if you want to enable lazy loading in Entity Framework, you don't need to do anything.


1 Answers

You are using AsNoTracking() somewhere in your code, Lazy Loading won't work when using AsNoTracking() method.

You have two options:

  1. Use the Include() method to load your relationships

  2. Ignore the warning and simply get null for your relationships

You can configure EF to ignore this error:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseLazyLoadingProxies()
        .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning))
        .UseSqlServer(@"Data Source=.;Initial Catalog=UniversityDb;Persist Security Info=True;User ID=admin;Password=asdasdsadasd");
}
like image 58
Sasan Avatar answered Oct 10 '22 21:10

Sasan