21

There are plenty of posts about how to disable lazy loading in Entity Framework, but the same techniques don't work in EF Core. I found the LazyLoadingEnabled property in the change tracker, but this doesn't seem to work at all.

Everything points to this in EF:

this.Configuration.LazyLoadingEnabled = false;

But, the Configuration property is missing in EF Core.

Here is an example of what I am talking about:

public class TestContext : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Address> Addresses { get; set; }

    public TestContext()
    {
        this.ChangeTracker.LazyLoadingEnabled = false;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        var connection = new SqliteConnection($"Data Source=Test.db");
        connection.Open();

        var command = connection.CreateCommand();

        command.CommandText = $"PRAGMA foreign_keys = ON;";
        command.ExecuteNonQuery();

        optionsBuilder.UseSqlite(connection);
        optionsBuilder.UseLazyLoadingProxies(false);

        base.OnConfiguring(optionsBuilder);
    }

    private static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        using (var context = new TestContext())
        {
            context.Database.EnsureCreated();

            var personKey = Guid.NewGuid().ToString();
            var addressKey = Guid.NewGuid().ToString();

            context.People.Add(new Entities.Person { PersonKey = personKey, BillingAddress = new Entities.Address { AddressKey = addressKey } });
            context.SaveChanges();
        }

        using (var context = new TestContext())
        {
            var people = context.People.ToList();

            foreach (var person in people)
            {
                if (person.BillingAddress == null) throw new Exception("The billing address wasn't loaded");
            }
        }
    }
}

The above throws an exception because BillingAddress is not getting loaded even though I turned lazy loading off.

I suspect this is a bug, but please tell me it isn't. I logged it here: https://github.com/aspnet/EntityFrameworkCore/issues/15802

You can download the sample here: https://www.dropbox.com/s/mimvgvcmibr7em2/EFSQLiteTest.7z?dl=0

12
  • 3
    There seems to be some confusion about what lazy loading off means. When the lazy loading is off, then EF Core won't load automatically related data - you have to explicitly do that using either eager or explicit loading. So the exception is expected and proves that EF Core does what it is supposed to do. In order to let EF Core load the related data automatically on first access of a navigation property, you need to do the opposite - turn the lazy loading on. Commented May 25, 2019 at 7:46
  • I've tried both, but neither load the BillingAddress. There is no way to load all child entities without extreme hacks. Commented May 25, 2019 at 7:55
  • I don't want Lazy Loading. I want to load all entities right at the start. Commented May 25, 2019 at 7:55
  • Disabling lazy loading won't do that. It doesn't mean "load everything automatically". Such option still doesn't exist, so my answer stackoverflow.com/questions/49593482/… still applies. Commented May 25, 2019 at 7:58
  • 3
    Eagerly loading all related data is rarely what you'll want; most of the times you'll just pull your entire database into local memory. Keep in mind that each navigation property access is another (LEFT OUTER) join, which will make the queries very slow as well as materialization due to the sheer amount of rows and columns returned. Frankly, I don't think such functionality should exist, and if the EF team plans it, it should require weird hacks. You seem to be confused about what is lazy loading and what is eager loading, you should probably read up on that. Commented May 25, 2019 at 16:08

1 Answer 1

38

If your problem is how to disable LazyLoading with EF Core try:

this.ChangeTracker.LazyLoadingEnabled = false;
Sign up to request clarification or add additional context in comments.

3 Comments

Worked for me to temporarily disable lazy loading when using table by hierarchy; I was getting a "An attempt was made to lazy-load navigation property..."
Since Lazy Loading is enabled at startup time / config time, I was lead to believe this flag didn't exist any more. Thank you so much for correcting my mistake!!
Isn't lazy loading disabled by default in EF Core?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.