cuealex
cuealex

Reputation: 21

Entity Framework Core 2.1 wrongly lazy loads some navigation properties but not others

I'm trying to solve the n+1 problem with my Entity Framework Core 2.1 project by ensuring that I only eager load my models.

The problem I'm having is that some associated models are being lazy loaded, but not others. And to be clear, I don't want anything lazy loaded at all, and I haven't enabled it explicitly. I don't believe this is expected behavior.

For instance, when I run this code the following code, it returns all of the included data as expected.

List<User> users = _context.Users
    .Include(u => u.Engine)
    .Include(u => u.ClientType)
    .Include(u => u.Organization)
    .Include(u => u.Role)
    .ToList();

However, if I remove all of the includes, about 90% of the users in the list will still have it's associated data included. I believe that this is why I'm getting the n+1 problem, despite using eager loading.

Why are only some of the associated models being lazy loaded? Why is anything be lazy loaded when I haven't enabled it? Could this be the root cause of my n+1 problem, despite my efforts to only use eager loading?

Upvotes: 1

Views: 66

Answers (1)

Adam Vincent
Adam Vincent

Reputation: 3821

EF Core does not enable lazy loading by default. You have to explicitly opt into it, and then mark your navigation properties as virtual. If you don't want lazy loading, make sure your OnConfiguring method does not call UseLazyLoadingProxies()

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
    // .UseLazyLoadingProxies() <- Only use this to enable lazy loading.
    .UseSqlServer(myConnectionString);

Upvotes: 1

Related Questions