Skip to content

Lazy Loading

Simon Hughes edited this page Oct 12, 2022 · 5 revisions
  1. In your <database>.tt file, set

    Settings.UseLazyLoading = true;
  2. Make sure your connection string has ;MultipleActiveResultSets=True in it.

EF Core additional steps

  • Install NuGet package: install-package Microsoft.EntityFrameworkCore.Proxies

  • Include UseLazyLoadingProxies(); in your database context. For example:

    // Either in startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
            .UseLazyLoadingProxies());
    
        ...
    }
    
    // Or in the database context
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=Demo;Integrated Security=True;MultipleActiveResultSets=True;Encrypt=false;TrustServerCertificate=true");
            optionsBuilder.UseLazyLoadingProxies();
        }
    }

Creating a website?

If you are creating a website then it's best not to use Lazy Loading as the database context is short-lived (typically less than a second), can add many round-trips to the database, and you tend to know up front what data you need for the view.

Prefer to .Include(p => p.Address) your related entities to load them up front in a single database call.

If you want to stay with lazy loading, that's completely fine, so long as you are aware of the extra round trips to the database. Further reading here.

Serializing your entities?

Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled. Further reading here