Skip to content

Lazy Loading

Simon Hughes edited this page Mar 20, 2026 · 7 revisions

Enable Lazy Loading

In Database.tt:

Settings.UseLazyLoading = true;

This marks all navigation properties as virtual, which is required for lazy loading.

EF Core — Additional Setup

EF Core lazy loading requires the Microsoft.EntityFrameworkCore.Proxies package:

Install-Package Microsoft.EntityFrameworkCore.Proxies

Then configure the DbContext to use lazy loading proxies:

Via Program.cs / Startup.cs (recommended):

services.AddDbContext<MyDbContext>(options => options
    .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
    .UseLazyLoadingProxies());

Via OnConfiguring:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(@"...;MultipleActiveResultSets=True;...")
        .UseLazyLoadingProxies();
}

Also add MultipleActiveResultSets=True to the connection string.

EF 6

Lazy loading is enabled by default when navigation properties are virtual. No additional packages are required. Add MultipleActiveResultSets=True to the connection string.

Warnings

Web applications: Lazy loading is generally a poor choice for web APIs and MVC applications:

  • Request contexts are short-lived; lazy loading can cause many extra database round-trips.
  • Serialization of lazy-loaded entities can trigger queries that load the entire database.
  • Use eager loading (.Include(p => p.Address)) or explicit loading instead.

Serialization: If you serialize entities with JSON (e.g., System.Text.Json, Newtonsoft.Json), lazy-loaded navigation properties will be queried during serialization. Use [JsonIgnore] or DTOs to avoid this.

Disabling Lazy Loading

Settings.UseLazyLoading = false;

Navigation properties are not marked virtual. Use .Include() for eager loading:

var orders = dbContext.Orders
    .Include(o => o.Customer)
    .Include(o => o.OrderItems)
    .ToList();

Clone this wiki locally