Covers Select projection versus Include in EF Core: generated SQL, columns and rows transferred, tracking behaviour of projected DTOs and entities, projecting collections and aggregates, and when Include is still correct.
For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.
Select are joined automatically; no Include is needed (and Include is ignored there).Include is still right when I load an aggregate to modify and save it, because I need tracked entities.The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.
"For anything that only reads, I project.
Includeanswers the question 'give me these entities and their related entities', so EF Core selects every mapped column of every included table, materialises full objects, and in a tracking query keeps a snapshot of each one for change detection. If the screen shows an order number, a customer name and a line count,Include(o => o.Customer).Include(o => o.Lines)drags in the customer's address and notes, every line's columns, and one row per line in the result set.With
Select(o => new OrderListItem(o.Id, o.Number, o.Customer.Name, o.Lines.Count())), EF Core generates SQL with exactly those columns: a join toCustomersfor the name and aCOUNT(*)subquery for the lines. No line rows are transferred at all. The DTO isn't an entity, so it isn't tracked, and I don't needAsNoTracking. One subtlety: if I project an entity inside the DTO, saynew { Order = o, ... }, that entity is still tracked in a tracking query.For example, at [company] our [order list endpoint] used
Includeon three navigations and returned entities through AutoMapper afterToList(). I changed it to aSelectprojection, and [the payload SQL went from ~40 columns and ~1,200 rows per page to 6 columns and 50 rows, with p95 dropping from ~420 ms to ~60 ms]. The mistake I see is mapping after materialisation, which keeps all the over-fetching; I use projection in the query, or a mapper'sProjectTo. Include is still right for commands: when I load an order to add a line and save, I want tracked entities. So: Include for writes, Select for reads."
Include |
Select projection |
|
|---|---|---|
| Columns | All mapped columns of each table | Only those referenced |
| Rows for a collection | One per child row (or split queries) | One per root, aggregates as subqueries |
| Result | Entities | DTOs / anonymous types |
| Tracked | Yes (unless AsNoTracking) |
DTOs no; entities inside the projection yes |
| Can save changes | Yes | No |
Large columns (nvarchar(max), blobs) |
Always loaded | Only if selected |
Use Include |
Use Select |
|---|---|
| Loading an aggregate to modify and save | API responses, lists, reports |
| Domain logic that needs the full entity | Summaries, counts, totals |
| Small graphs where the DTO would mirror the entity | Wide tables where you need few columns |
| Projection | SQL |
|---|---|
o.Lines.Count() |
Correlated COUNT(*) subquery |
o.Lines.Sum(l => l.Quantity * l.UnitPrice) |
SUM subquery |
o.Lines.Select(l => new LineDto(...)).ToList() |
LEFT JOIN with only those columns (or split) |
o.Lines.Any(l => l.IsBackordered) |
EXISTS |
An order list endpoint returned entities with three Includes and mapped after ToList(). Rewriting it as a projection cut SQL logical reads by [about 90%], memory per request from [~18 MB to ~1 MB] and p95 latency from [~420 ms to ~60 ms].
Checks that the candidate understands what Include loads versus what a projection loads, and links that to tracking and to read/write separation.
Green flags
Red flags
ToList() for every read.Include is needed for navigations used in Select.Include is about graph shape, not columns. EF Core must build complete entities so that change tracking, fix-up and later SaveChanges work. That means every mapped scalar property, plus keys for relationships:
Include(o => o.Customer).Include(o => o.Lines)
SELECT o.* (12 cols), c.* (15 cols), l.* (9 cols)
FROM Orders o JOIN Customers c ... LEFT JOIN OrderLines l ...
ORDER BY o.Id, c.Id, l.Id
rows = sum over orders of max(1, lines per order)
.Select(o => new OrderListItem(o.Id, o.Number, o.Customer.Name, o.Lines.Count()))
SELECT [o].[Id], [o].[Number], [c].[Name],
(SELECT COUNT(*) FROM [OrderLines] AS [l] WHERE [o].[Id] = [l].[OrderId])
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
EF Core walks the projection, records which columns each member needs, and builds the narrowest SELECT. Navigations referenced in the projection are joined automatically; Include is ignored when the final result isn't an entity type.
Cost ≈ rows × columns transferred (network, TDS parsing)
+ entities materialised (allocation)
+ tracking (snapshot copy + identity map entry per entity)
Projection reduces all three. A tracked entity costs roughly twice its own memory because EF Core stores a snapshot of original values for DetectChanges.
| Projection result | Tracked in a tracking query? |
|---|---|
new OrderDto(...) (only scalars) |
No |
| Anonymous type with scalars | No |
new { Order = o, LineCount = ... } |
o is tracked |
o.Customer (an entity) |
Yes |
Mapping after materialisation (mapper.Map<List<Dto>>(await q.ToListAsync())) still runs the Include-style query. Use expression-based mapping that EF Core can translate: AutoMapper's ProjectTo<TDto>(), Mapster's ProjectToType<TDto>(), or a hand-written static Expression<Func<Order, OrderDto>> you reuse. Check that the mapping expression contains only translatable members.
A narrow projection can be served entirely from a covering index (INCLUDE columns), avoiding key lookups into the clustered index. Include of whole entities almost never can.
Include and with Select; compare ToQueryString() output and column counts.[MemoryDiagnoser] on 1,000 orders with 10 lines each; compare allocations.new { Order = o, Count = o.Lines.Count() } and check db.ChangeTracker.Entries().Count().Include to a query that ends in a DTO Select and confirm in the SQL that it changes nothing.Read side projects, write side includes.
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
public sealed record OrderListItem(int Id, string Number, string CustomerName, int LineCount, decimal Total);
public sealed class OrderReads(ShopDbContext db)
{
// Read: only five values per order leave SQL Server; nothing is tracked.
public Task<List<OrderListItem>> ListAsync(int customerId, CancellationToken ct) =>
db.Orders
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.PlacedAt)
.Select(o => new OrderListItem(
o.Id,
o.Number,
o.Customer.Name, // join, no Include needed
o.Lines.Count(), // COUNT subquery
o.Lines.Sum(l => l.Quantity * l.UnitPrice))) // SUM subquery
.Take(50)
.ToListAsync(ct);
}
public sealed class AddLineHandler(ShopDbContext db)
{
// Write: we need the tracked aggregate so SaveChanges can insert the new line.
public async Task HandleAsync(int orderId, int productId, int quantity, CancellationToken ct)
{
var order = await db.Orders
.Include(o => o.Lines)
.SingleAsync(o => o.Id == orderId, ct);
order.AddLine(productId, quantity); // domain rule checks run on the full aggregate
await db.SaveChangesAsync(ct);
}
}
-- ListAsync
SELECT TOP(@p) [o].[Id], [o].[Number], [c].[Name],
(SELECT COUNT(*) FROM [OrderLines] AS [o0] WHERE [o].[Id] = [o0].[OrderId]),
(SELECT COALESCE(SUM(CAST([o1].[Quantity] AS decimal(18,2)) * [o1].[UnitPrice]), 0.0)
FROM [OrderLines] AS [o1] WHERE [o].[Id] = [o1].[OrderId])
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[CustomerId] = @customerId
ORDER BY [o].[PlacedAt] DESC
Include for read-only lists. Why it is wrong: it loads every column of every included table and tracks the entities. Instead: project with Select into a DTO.ToListAsync(). Why it is wrong: the over-fetching already happened in SQL. Instead: map in the query with Select or an expression-based mapper (ProjectTo, ProjectToType).Select (or a static Expression<Func<TEntity,TDto>>) for hot paths, and check any mapper projection with ToQueryString().Include to a query that ends in a projection. Why it is wrong: EF Core ignores it; it only adds confusion. Instead: reference the navigation in the Select.AsNoTracking() to a pure DTO projection. Why it is wrong: DTOs are never tracked, so it does nothing. Instead: add it only when the result contains entities.AsNoTracking().SaveChanges does nothing. Instead: load the tracked entity (or use ExecuteUpdate) for writes.This is effectively CQRS at the query level: the write side loads aggregates with Include so invariants run on complete objects; the read side projects exactly what the screen needs. It removes most N+1 and over-fetching problems without any extra infrastructure.
I measure the difference with SQL logical reads (SET STATISTICS IO ON or Query Store) and allocations per request, not just latency, because over-fetching often hides until load rises.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Select into DTO |
Reads, lists, reports | A DTO per use case | When you need to modify and save |
Include + tracking |
Command handlers modifying an aggregate | Wide rows, tracking memory | Read-only screens |
Include + AsNoTracking |
Read-only but you genuinely need full entities (e.g. domain logic) | Still over-fetches | High-volume lists |
ProjectTo (mapper) |
Many DTOs mirroring entities | Hidden mapping config, translation surprises | Complex logic in mapping profiles |
EF Core does not load navigation properties unless you ask. There are three ways:
Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).
The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.
With EF Core, IQueryable<T> means "a query not yet sent": each LINQ operator adds to an expression tree, and the provider translates the whole tree into one SQL statement when you enumerate it. IEnumerable<T> means "objects in memory": operators are compiled delegates that run in your process over rows already fetched.
Where you get: Queryable.Where(Expression<...>) or Enumerable.Where(Func<...>).AsEnumerable() is only a cast and ToList() runs the query straight away, but after either one (or a method that returns IEnumerable<T>) every later filter, sort and Take runs in C#. The SQL that is sent no longer contains them, so the database can't use an index or TOP, and far more rows cross the wire.The trade-off: keep it IQueryable while the database can do the work, and switch to memory only for the last step SQL can't do.
Store it as a static Expression<Func<Order, OrderListItem>> and pass it to Select. EF Core inlines the expression tree and translates it, so every query that reuses it still selects only the projected columns, and the DTO shape is defined once instead of copied into each query. A normal method (o => ToDto(o)) won't translate except as final client evaluation, which loads whole entities. Being static, the expression is built once with no per-call cost. For nested reuse, libraries like LinqKit (Invoke/Expand) or a mapper's ProjectTo help.
How to tell it (STAR)
**S:** At [company], our order list endpoint on Azure SQL had crept from [150 ms] to [420 ms] p95 as data grew, and customer-service staff were complaining. **T:** I was asked to [find and fix the regression] without a schema redesign. **A:** I pulled the SQL from Application Insights and saw three Includes returning about 40 columns and a row per order line, then mapped to DTOs after materialising. I rewrote the query as a Select projection so EF Core fetched six columns and computed counts and totals as subqueries, and added a covering index. I also added a checklist rule that query handlers project instead of including. **R:** p95 dropped to [~60 ms], logical reads fell by [~90%], and memory per request went from [18 MB to about 1 MB].
Last updated 23 Nov 2026.