For a read-only EF Core 10 endpoint returning playlist DTOs, why project related data with Select instead of Include, and what happens to an Include placed before that Select?
answer
- shape the SQL, not the entity graph
- navigations inside Select need no Include
- only the projected columns are read
- no entity in the result, nothing tracked
- includes expand only on returned entities
basics
~20 sA Select projection reads only the columns the DTO needs, follows navigations without Include, returns untracked objects and cannot lazy-load. An Include before it has no effect when the final projection returns no entity, so it should be removed.
solid answer
~40 s`Include(p => p.Tracks).ThenInclude(t => t.Artist)` materializes whole `Playlist`, `Track` and `Artist` entities - every mapped column - and in a tracking query registers each in the change tracker, only for the endpoint to copy three fields into a DTO. `Select(p => new PlaylistView(p.Name, p.Tracks.Select(t => new TrackRow(t.Title, t.Artist.Name, t.Album.Title)).ToList()))` lets EF Core translate the navigations into joins itself and read just those columns; the DTOs are not tracked, carry no proxies that could lazy-load, and have no back-references for the JSON serializer to cycle on. An `Include` in front of that `Select` changes nothing: EF Core expands includes only on entity instances the final projection returns, and a mapped property access becomes a plain column. Include stays the right tool when the handler needs the entities themselves, typically to modify them and call `SaveChanges`.
code
csharp · 16 linespublic record TrackRow(string Title, string Artist, string Album);
public record PlaylistView(string Name, List<TrackRow> Tracks);
app.MapGet("/admin/playlists/{id:int}", async (int id, MusicDb db) =>
{
var view = await db.Playlists
.Where(p => p.Id == id)
.Select(p => new PlaylistView(
p.Name,
p.Tracks.OrderBy(t => t.Title)
.Select(t => new TrackRow(t.Title, t.Artist.Name, t.Album.Title))
.ToList()))
.SingleOrDefaultAsync();
return view is null ? Results.NotFound() : Results.Ok(view);
});go deeper
Recall that Select can read related data through navigations directly, without Include, and returns only what you name.
Explain what each approach reads and tracks, and why an Include before a DTO projection is ignored.
Default read endpoints to projections and write paths to Include, and catch entity-returning endpoints that over-read, cycle in JSON or lazy-load while serializing.
Set the read/write split as a codebase convention, and judge where projection DTOs belong so query shape stays owned by the endpoint that needs it.
## Two ways to read related data An **Include** asks EF Core to load related **entities** - full objects with every mapped column - alongside the root. A **projection** is a `Select` that builds some other shape, usually a DTO (data transfer object: a plain class or record that carries exactly what the response needs). Both can read data from several tables in one query; they differ in what comes back. | Aspect | `Include` / `ThenInclude` | `Select` projection | |---|---|---| | Columns read | every mapped column of every included entity | only the columns the projection names | | Result | entity instances | DTOs, anonymous types or scalars | | Change tracking (default tracking query) | every entity is tracked | nothing tracked if no entity is in the result | | Lazy-loading proxies | returned entities can still lazy-load | DTOs cannot lazy-load | | JSON serialization | two-way navigations can form cycles (track to playlist and back) | DTO shape is acyclic by design | | Saving changes | modify and call `SaveChanges` | read-only | ## How navigations translate inside Select Inside a projection, a navigation is part of the query expression, not a property read on an object. EF Core translates it: - a **reference navigation** such as `t.Artist.Name` becomes a join and one column; - a **collection navigation** such as `p.Tracks.Select(...).ToList()` becomes a correlated collection, materialized into a list on each DTO; - **aggregates** such as `p.Tracks.Count()` or `p.Tracks.Sum(t => t.DurationSeconds)` stay in SQL and return one value. None of this needs an `Include`. That is the most common misconception: "I must include `Artist` before I can read `t.Artist.Name` in the `Select`." You do not - the projection itself tells EF Core what to read. ## Nulls and optional navigations In a projection, `t.Album.Title` is translated to SQL, so an optional album that is missing yields `null` from the outer join rather than a `NullReferenceException` in C#. The DTO property should therefore be declared nullable (`string? Album`) when the relationship is optional. The same expression over loaded entities in memory - after an `Include` - would throw when `Album` is `null`, which is one more reason the two approaches are not interchangeable. ## What happens to an Include before the Select EF Core applies include paths while expanding the **final projection**: wherever that projection returns an entity instance, the pending includes for it are expanded; wherever it reads a mapped property, the expression becomes a column and no include applies. So: 1. `db.Playlists.Include(p => p.Tracks).Select(p => new { p.Name, Count = p.Tracks.Count() })` - the result contains no `Playlist` entity; the `Include` is ignored and the SQL computes a count. 2. `db.Playlists.Include(p => p.Tracks).Select(p => new { Playlist = p, p.Name })` - the result contains the entity `p`, so its `Tracks` are included and `p` is tracked in a tracking query. Position matters: an `Include` written **after** such a `Select` is not ignored but rejected - EF Core throws an `InvalidOperationException` telling you to apply `Include` before the `Select`. A leftover `Include` before a DTO projection is therefore harmless but misleading: a reviewer reads it as "this query loads tracks" when it does not. ## When Include is still right - **Commands, not queries:** the handler loads a playlist with its tracks, reorders them and calls `SaveChanges`; it needs tracked entities. - **Domain logic on the entity:** behaviour lives on the entity class and needs its navigations populated. - **Small, stable aggregates** returned in full, where writing a DTO adds nothing. ## The senior judgement 1. Default to **projection for read endpoints** - list pages, admin grids, API responses. 2. Use **Include for write paths** that load an aggregate to change it. 3. Treat entities in HTTP responses as a smell: they leak columns, invite cycles and, with proxies, lazy loads during serialization. 4. Check the generated SQL when it matters; `ToQueryString()` shows what a projection actually reads. The principle: a read endpoint should ask the database for the response's shape, not for an object graph it then throws most of away.
- In a tracking query, is anything tracked when the projection is new { Playlist = p, TrackCount = p.Tracks.Count() }?Yes - the `Playlist` instance. EF Core tracks entity instances contained in a projection's result, even inside an anonymous type, and applies any `Include` for them. Only results that contain no entity at all, such as pure DTOs or scalars, leave the change tracker empty.
- A teammate adds Include(p => p.Tracks) before a DTO Select "so the tracks are loaded" - what do you tell them?That it does nothing: EF Core expands includes only on entities the final projection returns, and the DTO projection already reads the track columns through the navigation. Remove the `Include` so the query reads as what it does, and check `ToQueryString()` if in doubt.
- You must Include a navigation before reading its columns inside Select.
- An Include before a DTO Select makes EF Core load full Track entities.
- Projected DTOs are tracked and saved back by SaveChanges.
- A projection first materializes the entities and then maps them, so it reads more.
- Include is the only way to read related tables in one EF Core query.