skip to content

An EF Core 10 admin page lists a playlist's tracks with artist and album and logs one SQL query per track - how do lazy-loading proxies cause that, and how do you fix it?

level: middleimportance: must knowfreq 70%

answer

  1. an opt-in package and one options call
  2. virtual navigations on unsealed classes
  3. the getter sends the query
  4. synchronous I/O inside the loop
  5. CoreEventId.NavigationLazyLoading at Debug level

basics

~20 s

With UseLazyLoadingProxies, each virtual navigation loads on first access, so reading track.Artist and track.Album in the loop sends queries per track. Load them up front with Include/ThenInclude or a Select projection, and switch lazy loading off.

solid answer

~40 s

Lazy loading is opt-in: the `Microsoft.EntityFrameworkCore.Proxies` package plus `UseLazyLoadingProxies()` makes EF Core materialize generated subclasses whose overridden `virtual` navigation getters query the database the first time they are read. The page loads the playlist, then `foreach` touches `track.Artist.Name` and `track.Album.Title` - up to two synchronous round trips per track, all hidden behind property access. The fix is to state the load shape in the query: `Include(p => p.Tracks).ThenInclude(t => t.Artist)` plus the album branch, or better a `Select` projection of just the columns shown. To stop it recurring, turn lazy loading off for that context (`ChangeTracker.LazyLoadingEnabled = false`) or per navigation with `EnableLazyLoading(false)` (EF Core 8+), and in development make `CoreEventId.NavigationLazyLoading` throw via `ConfigureWarnings` so any hidden load fails a test.

code

csharp · 12 lines
csharp
builder.Services.AddDbContext<MusicDb>(o => o
    .UseNpgsql(builder.Configuration.GetConnectionString("Music"))
    .UseLazyLoadingProxies()
    .ConfigureWarnings(w => w.Throw(CoreEventId.NavigationLazyLoading)));

public class Track
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public virtual Artist Artist { get; set; } = null!;
    public virtual Album Album { get; set; } = null!;
}

go deeper

for a junior

Recall the setup - the Proxies package, UseLazyLoadingProxies(), virtual navigations - and that reading such a navigation can send a query.

for a middle

Explain how the proxy subclass's getter triggers a synchronous query per navigation per row, and fix the page with Include/ThenInclude or a projection.

for a senior

Show the production habits: lazy loading off or NavigationLazyLoading set to throw in tests, no proxy entities handed to serializers, and awareness of the disposed-context exception.

for a principal

Argue whether lazy loading belongs in a web app at all, and how to retire it from an existing codebase without breaking pages that silently depend on it.

## How EF Core turns lazy loading on EF Core never lazy-loads by default. There are two opt-in routes. **Proxies** - the common one: 1. Reference the `Microsoft.EntityFrameworkCore.Proxies` package (it generates subclasses with Castle.Core). 2. Call `UseLazyLoadingProxies()` on the `DbContextOptionsBuilder`, next to `UseNpgsql(...)`. 3. Make navigations `virtual` and keep entity classes unsealed, so EF Core can create a subclass whose getter override loads the navigation on first access. The model is validated when it is built: a sealed entity class, or a navigation that is not `virtual`, throws an `InvalidOperationException` ("Property 'Track.Album' is not virtual..."). `UseLazyLoadingProxies(o => o.IgnoreNonVirtualNavigations())` relaxes the second rule, leaving non-virtual navigations simply not lazy-loaded. **`ILazyLoader` injection** - no proxies: an entity takes an `ILazyLoader` (from `Microsoft.EntityFrameworkCore.Abstractions`) in a constructor, and each navigation getter calls `LazyLoader.Load(this, ref _album)`. Entities stay ordinary classes, need no `virtual`, and can also load after being attached; EF Core can even inject an `Action<object, string>` delegate named `lazyLoader` to keep EF types out of the domain model entirely. ## Where the per-track queries come from ```csharp var playlist = await db.Playlists.SingleAsync(p => p.Id == id); // 1 query foreach (var track in playlist.Tracks) // +1: tracks { rows.Add(new(track.Title, track.Artist.Name, // +1 per track track.Album.Title)); // +1 per track } ``` Nothing in that code looks like data access. Each first read of `Artist` or `Album` on a track asks the context to load that navigation, and EF Core logs `CoreEventId.NavigationLazyLoading` ("The navigation 'Track.Artist' is being lazy-loaded.") at **Debug** level before the query - which is why default logging rarely shows it. Three things make it worse in ASP.NET Core: - **Synchronous I/O.** A property getter cannot be awaited, so every lazy load blocks a thread-pool thread for a full round trip. - **Serialization.** Returning proxy entities from an endpoint lets the JSON serializer walk every `virtual` navigation, loading the graph row by row (and running into cycles). - **Lifetime.** A lazy load after the scoped `DbContext` is disposed or returned to the pool logs `LazyLoadOnDisposedContextWarning`, which EF Core configures to **throw** by default. ## Fixing it | Fix | What it changes | |---|---| | `Include(p => p.Tracks).ThenInclude(t => t.Artist)` plus `Include(p => p.Tracks).ThenInclude(t => t.Album)` | loads the graph in one query; the getters find loaded navigations and send nothing | | `Select` into a `TrackRow(Title, ArtistName, AlbumTitle)` | reads only the shown columns; no entities, so no proxies to trigger | | `db.ChangeTracker.LazyLoadingEnabled = false` | this context instance stops lazy loading; unloaded navigations stay null | | `.Navigation(t => t.Album).EnableLazyLoading(false)` | one navigation opts out in the model (EF Core 8+) | | `ConfigureWarnings(w => w.Throw(CoreEventId.NavigationLazyLoading))` | any lazy load throws - a tripwire for development and tests | The first two fix the page; the last three stop the next page from regressing. Many teams go further and drop `UseLazyLoadingProxies` from web apps altogether: the EF Core performance guidance recommends avoiding lazy loading because eager or explicit loading makes each round trip visible in code. ## Behaviours that changed in EF Core 8 - Lazy loading now also works on entities returned by a **no-tracking** query, until the context that ran the query is disposed or the entity is explicitly detached. - `EnableLazyLoading(false)` lets a single navigation opt out while the rest of the model keeps lazy loading. Both apply to proxies and to `ILazyLoader` injection, and both are current in EF Core 10. ## Detecting it in a running app - Raise the `Microsoft.EntityFrameworkCore.Infrastructure` log category to Debug in Development; each lazy load then logs a `NavigationLazyLoading` line naming the entity and navigation. - Watch the command log (`Microsoft.EntityFrameworkCore.Database.Command`): a burst of identical `SELECT` statements that differ only in the key parameter is the signature. - In integration tests, the `ConfigureWarnings(...Throw(CoreEventId.NavigationLazyLoading))` tripwire turns the same symptom into a failing test. ## What to say in an interview 1. Name the mechanism: proxy subclass, overridden `virtual` getter, a query on first access. 2. Count the cost: one query for the parent, then up to one per navigation per row. 3. Fix the page with `Include`/`ThenInclude` or a projection. 4. Prevent regressions: lazy loading off, or `NavigationLazyLoading` configured to throw in tests.

  • How do you get lazy loading without proxies or virtual navigations?
    Inject `ILazyLoader` into the entity through a constructor parameter and call `LazyLoader.Load(this, ref _field)` in each navigation getter; the interface lives in the small `Microsoft.EntityFrameworkCore.Abstractions` package. To avoid any EF type in the model, take an `Action<object, string>` constructor parameter named `lazyLoader` instead. The classes need not be unsealed or have virtual members.
  • What happens if code touches an unloaded proxy navigation after the request's DbContext is disposed?
    The lazy loader logs `CoreEventId.LazyLoadOnDisposedContextWarning`, and EF Core configures that event to throw by default, so the access fails with an `InvalidOperationException`. It typically shows up when an entity escapes its scope, for example into a background task or a cache.
  • How would you make a test fail whenever a handler lazy-loads?
    Configure the test context with `ConfigureWarnings(w => w.Throw(CoreEventId.NavigationLazyLoading))`. Every lazy load then raises an `InvalidOperationException` naming the navigation, so a missing `Include` fails the test instead of silently adding queries.

A lazy-loading proxy is a library index card that sends a runner to the stacks the moment you look at it: one card is harmless, but reading a 200-card drawer one card at a time sends 200 runners.

  • EF Core lazy-loads navigations by default once a relationship is configured.
  • Lazy-loading proxies work with sealed entity classes and non-virtual navigations.
  • Lazy loading is asynchronous, so it does not block request threads.
  • UseChangeTrackingProxies is what enables lazy loading in EF Core.
  • A lazy load after the DbContext is disposed just returns null silently.

Assumes EF Core 10; lazy loading from no-tracking queries and the per-navigation EnableLazyLoading(false) opt-out were added in EF Core 8.