📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

For a read-only API endpoint, would you load data with Include or project it with Select into a DTO? Explain the difference in the SQL, over-fetching, what each means for change tracking, and when Include is still the right choice.

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.

Mid-Level Theory Intermediate change-tracking dto ef-core include over-fetching projection

🎯 Key points

  • Include always adds joins and loads whole entities: every mapped column of every included table
  • Select loads only the columns referenced; navigations in Select become joins only when used
  • Projected DTOs are never tracked, so AsNoTracking is redundant there; entities inside a projection are tracked
  • Aggregates in a projection (Count, Sum, Any) become SQL subqueries, no rows loaded
  • A narrow projection can be served by a covering index, avoiding key lookups
  • Include + tracking is right when you load an aggregate to change and save it
  • Fewer bytes over the network matters more as latency and row counts grow
  • Mapping libraries: only expression-based mapping (ProjectTo) avoids over-fetching; mapping after ToList keeps it

⏱ 30-second answer

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.

  • Navigations used inside 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.

🗣 Full answer (senior)

How I would answer this in an interview

"For anything that only reads, I project. Include answers 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 to Customers for the name and a COUNT(*) 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 need AsNoTracking. One subtlety: if I project an entity inside the DTO, say new { Order = o, ... }, that entity is still tracked in a tracking query.

For example, at [company] our [order list endpoint] used Include on three navigations and returned entities through AutoMapper after ToList(). I changed it to a Select projection, 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's ProjectTo. 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 versus Select

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

When to use which

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

Projecting collections

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

Production example

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].

🔍 What the interviewer is checking

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

  • Explains column and row differences in the SQL.
  • Knows projected DTOs aren't tracked but projected entities are.
  • Mentions aggregates becoming subqueries.
  • Keeps Include for loading aggregates to modify.

Red flags

  • Uses Include plus mapping after ToList() for every read.
  • Thinks Include is needed for navigations used in Select.
  • Can't say when Include is the right choice.

📚 Learn in depth

1. What Include actually asks for

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)

2. What projection asks for

.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.

3. Cost model

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.

4. Tracking rules for projections

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

5. Mapping libraries

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.

6. Index coverage

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.

Try it yourself

  1. Write the same list query with Include and with Select; compare ToQueryString() output and column counts.
  2. Use BenchmarkDotNet with [MemoryDiagnoser] on 1,000 orders with 10 lines each; compare allocations.
  3. Project new { Order = o, Count = o.Lines.Count() } and check db.ChangeTracker.Entries().Count().
  4. Add Include to a query that ends in a DTO Select and confirm in the SQL that it changes nothing.
  5. Create a covering index for the projected columns and compare the execution plan (look for the disappearance of Key Lookup).

💻 Code

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

⚠ Common mistakes

  • Mistake: Using 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.
  • Mistake: Mapping to DTOs after 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).
  • Mistake: Trusting a mapping library's projection blindly. Why it is wrong: mapping profiles with custom resolvers or C# methods may not translate, or may pull whole entities into the final client projection; the SQL is hidden behind configuration. Instead: prefer a hand-written Select (or a static Expression<Func<TEntity,TDto>>) for hot paths, and check any mapper projection with ToQueryString().
  • Mistake: Adding 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.
  • Mistake: Adding 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.
  • Mistake: Projecting entities inside an anonymous type and assuming nothing is tracked. Why it is wrong: entity instances in a projection are tracked in a tracking query. Instead: project scalars, or add AsNoTracking().
  • Mistake: Projecting and then trying to save changes. Why it is wrong: DTOs aren't tracked, so SaveChanges does nothing. Instead: load the tracked entity (or use ExecuteUpdate) for writes.
  • Mistake: Calling C# helpers inside the projection that need navigation data. Why it is wrong: a helper receiving the whole entity forces EF Core to fetch all its columns for client evaluation. Instead: pass only scalar values into client helpers, or compute in SQL.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions eager, explicit or lazy loading. Why: Checks the loading strategies behind Include.
    How to answer

    EF Core does not load navigation properties unless you ask. There are three ways:

    • Eager loading: Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().
    • Explicit loading: await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.
    • Lazy loading: with 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.

  2. When: Candidate maps after ToList() or mentions AsEnumerable(). Why: Checks where the query stops being SQL.
    How to answer

    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.

    • The compile-time type decides which 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.

  3. When: Candidate says they write a DTO per use case. Why: Checks practical projection reuse and expression trees.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Order list endpoint slowed by Include and post-query mapping
Situation
An [e-commerce] API on Azure SQL in Australia East served an order list to [~3,000] customer-service users. Each page showed 50 orders with customer name, line count and total.
Signals
p95 latency on `GET /orders` rose from [~150 ms] to [~420 ms] as order history grew; Application Insights showed one SQL dependency per request returning [~1,200] rows; memory per request around [18 MB]; Gen 2 GC count rising on dotnet-counters.
Investigation
Captured the SQL with `ToQueryString()` and Application Insights dependency telemetry: three `Include`s produced ~40 columns and one row per order line. The code mapped to DTOs with AutoMapper after `ToListAsync()`. `SET STATISTICS IO ON` showed [~25,000] logical reads per page; the execution plan had key lookups for the wide columns.
Resolution
Immediate: added `AsNoTracking()` to cut tracking memory. Real fix: replaced Include + mapping with a `Select` projection (name via join, `Count()` and `Sum()` subqueries), and added a covering index on `(CustomerId, PlacedAt) INCLUDE (Number, Total)`.
Prevention
Code-review checklist item: read endpoints must project; an architecture test flags handlers in the Queries folder that call `Include`; a performance test with production-like data volumes runs in CI; dashboards on SQL logical reads per endpoint from Query Store.

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].

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me