skip to content

In EF Core 10, how does explicit loading through Entry().Collection() and Entry().Reference() work, and when do you call Query() instead of Load()?

level: middleimportance: should knowfreq 45%

answer

  1. load later, on demand, on purpose
  2. db.Entry(entity).Collection(...).LoadAsync()
  3. Reference(...) for a single related entity
  4. IsLoaded turns a repeat Load into a no-op
  5. Query() returns IQueryable<TRelated>

basics

~20 s

Explicit loading fetches one navigation of an entity you already hold: db.Entry(x).Collection(...) or .Reference(...), then LoadAsync(). Query() instead returns an IQueryable over that navigation, to count, filter or page related rows without loading them all.

solid answer

~40 s

After `var playlist = await db.Playlists.SingleAsync(...)`, `await db.Entry(playlist).Collection(p => p.Tracks).LoadAsync()` sends one query for that playlist's tracks and fills the navigation; `db.Entry(track).Reference(t => t.Album).LoadAsync()` does the same for a single related entity. `Load` sets the navigation's `IsLoaded` flag, and a later `Load` on a loaded navigation is a no-op. `Query()` hands back an `IQueryable<Track>` scoped to that navigation, so `...Collection(p => p.Tracks).Query().CountAsync()` runs a `COUNT` and `...Query().Where(...).LoadAsync()` loads a subset - without marking the navigation loaded. Use explicit loading when you decide what to fetch only after seeing the parent; each call is its own round trip, so in a loop it becomes the per-row pattern Include avoids. Since EF Core 8 it also works on entities from a no-tracking query.

code

csharp · 13 lines
csharp
var playlist = await db.Playlists.SingleAsync(p => p.Id == id);
var entry = db.Entry(playlist);

// Newest 20 tracks only; Tracks is NOT marked loaded afterwards
await entry.Collection(p => p.Tracks)
    .Query()
    .OrderByDescending(t => t.AddedAt)
    .Take(20)
    .LoadAsync();

// The album of one track the editor opened
var track = playlist.Tracks.First(t => t.Id == trackId);
await db.Entry(track).Reference(t => t.Album).LoadAsync();

go deeper

for a junior

Recall the calls: db.Entry(x).Collection(...) for many, .Reference(...) for one, then LoadAsync(), and that it is a separate query you write yourself.

for a middle

Explain the IsLoaded flag, why a repeat Load is a no-op, and how Query() turns a navigation into an IQueryable for counts and slices that leave the flag unset.

for a senior

Show when explicit loading beats Include - decisions made after the parent loads, slices of large collections - and spot it inside a loop as a per-row round-trip bug.

for a principal

Weigh explicit loading against projections and eager loading as a team convention, so the number of round trips per request stays visible in code review.

## Three ways EF Core gets related data EF Core offers three loading strategies for **navigations** (properties that point at related entities): | Strategy | When the SQL runs | Where it is written | Can be awaited | |---|---|---|---| | Eager (`Include`) | with the parent query | in the query | yes | | **Explicit** (`Entry(...).Load`) | when you call it | a separate statement in your code | yes (`LoadAsync`) | | Lazy (proxies or `ILazyLoader`) | on first property access | nowhere visible | no - property getters are synchronous | Explicit loading is the middle option: the extra round trip is visible in code, it is asynchronous, and it runs only when the code decides it needs the data. ## The Entry API, step by step 1. `db.Entry(playlist)` returns an `EntityEntry<Playlist>` - EF Core's handle on that entity in the change tracker. 2. `.Collection(p => p.Tracks)` returns a `CollectionEntry<Playlist, Track>` for a collection navigation; `.Reference(t => t.Album)` returns a `ReferenceEntry<Track, Album>` for a single-valued one. Using the wrong one does not compile. 3. `.LoadAsync()` (or `Load()`) builds a query for the related rows by foreign key, runs it, and fills the navigation. 4. The entry's `IsLoaded` flag becomes `true`; a further `Load` or `LoadAsync` on the same navigation returns without querying. `Include` sets the same flag. ```csharp var playlist = await db.Playlists.SingleAsync(p => p.Id == id); var tracks = db.Entry(playlist).Collection(p => p.Tracks); var count = await tracks.Query().CountAsync(); // SELECT COUNT(*) only if (count <= 500) { await tracks.LoadAsync(); // loads all and sets IsLoaded } ``` ## Load versus Query() | Call | What it does | Sets `IsLoaded` | |---|---|---| | `Collection(...).LoadAsync()` | loads every related row into the navigation | yes | | `Collection(...).Query().CountAsync()` | runs an aggregate; loads no entities | no | | `Collection(...).Query().Where(...).LoadAsync()` | loads a filtered subset; in a tracking context the rows join the navigation through fix-up | no | | `Reference(...).LoadAsync()` | loads the single related entity | yes | `Query()` is the reason explicit loading is more than "lazy loading you call by hand": it is an ordinary LINQ query rooted at the navigation, so you can count tracks, fetch the newest twenty, or check `AnyAsync()` without materializing the whole collection. Because a subset is not the whole collection, EF Core does not mark the navigation loaded after a `Query()`-based load - a later `LoadAsync()` still runs and fetches the rest. ## Untracked entities since EF Core 8 Up to EF Core 7 explicit loading assumed a tracked entity. **EF Core 8** added loading of navigations on entities returned by a no-tracking query, and unlike lazy loading this can be done asynchronously. Because an untracked entity has no identity resolution, loading into a collection that already holds some items can create duplicate instances; `LoadAsync(LoadOptions.ForceIdentityResolution)` prevents that at some extra cost (for tracked entities it behaves exactly like the default). ## When to use it - and when not - **Good fit:** a handler loads a playlist, checks permissions or a feature flag, and only then needs the tracks; or it needs a count or a small slice of a large collection. - **Good fit:** a reference needed for one entity in a hundred, where `Include` would pull it for all hundred. - **Poor fit:** a loop that calls `LoadAsync` for every parent in a list - each iteration is a round trip, which is exactly the per-row pattern that eager loading or a projection avoids. - **Poor fit:** read-only pages that only display columns; a `Select` projection reads less. ## Explicit loading inside an ASP.NET Core handler The calls belong to the request-scoped `DbContext` that `AddDbContext` registers, so they must run before the handler returns - an entity that escapes into a background task cannot be loaded through a context the request already disposed. Pass the request's cancellation token: `LoadAsync(cancellationToken)` and the `Query()` operators all accept one, so a client that disconnects stops the extra round trip as well. And keep the decision close to the code that needs the data; a helper that quietly calls `LoadAsync` is as hard to see in review as a lazy load. A practical rule: if you know before the query runs what the handler needs, say it in the query with `Include` or `Select`; if you only know afterwards, load it explicitly, and use `Query()` when you need less than the whole collection.

  • After loading only the newest 20 tracks through Query(), what does a later Collection(p => p.Tracks).LoadAsync() do?
    It queries the database. Only `Load`/`LoadAsync` on the entry sets `IsLoaded`; a load through `Query()` does not, because EF Core cannot know the subset is the whole collection. The full load fetches every track; in a tracking context the 20 already tracked instances are kept rather than duplicated.
  • Why is calling LoadAsync for each playlist in a list of fifty a problem, and what do you write instead?
    Each `LoadAsync` is its own round trip, so fifty playlists cost fifty-one statements and the latency adds up per request. If every playlist needs its tracks, load them with the list via `Include(p => p.Tracks)`, or project the needed columns with `Select`; keep explicit loading for data you decide on per entity.

  • Calling Load twice on the same collection queries the database twice.
  • Collection(...).Query().CountAsync() loads all the tracks and counts them in memory.
  • Explicit loading only works when lazy-loading proxies are enabled.
  • Explicit loading is merged into the original query the way Include is.
  • Explicit loading cannot be awaited because it runs on property access.

Assumes EF Core 10; explicit loading on entities from a no-tracking query, with LoadOptions, was added in EF Core 8.