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

📚 Interview question

An EF Core query for 50 orders with three collection Includes takes seconds, and SQL Server reports hundreds of thousands of rows returned. Why does this happen, how do you confirm it is cartesian explosion, and how do you choose between projection, AsSplitQuery() and loading the collections separately?

Covers why several collection Includes multiply rows in a single JOIN query, how to measure and confirm cartesian explosion (row counts, logical reads, the EF Core multiple-collection warning), and how to pick projection, split queries or separate loads.

Mid-Level Theory Intermediate cartesian-explosion ef-core include query-performance split-queries sql-server

🎯 Key points

  • Each collection Include adds a LEFT JOIN; sibling collections multiply rows (parent x A x B x C)
  • Parent columns are duplicated on every row: network and materialisation cost
  • Confirm with ToQueryString, actual rows on the plan's operators, SET STATISTICS IO
  • EF Core logs MultipleCollectionIncludeWarning when no splitting behaviour is set
  • Projection: return only needed columns and aggregates, often the best fix
  • AsSplitQuery: one round trip per collection; no consistent snapshot without a transaction
  • Separate explicit loads or Contains queries when the shape varies
  • Measure before and after: duration, rows returned, logical reads, allocations

⏱ 30-second answer

With a single query, each collection Include becomes a LEFT JOIN, and sibling collections multiply: 50 orders x 20 lines x 10 notes x 30 status events is 300,000 rows, with the order's columns repeated on every one. That is cartesian explosion: SQL Server, the network and EF Core's materialiser all process far more rows than the result needs. I confirm it by comparing rows returned in the actual execution plan or SET STATISTICS IO with the number of entities, reading the SQL via ToQueryString(), and checking for EF Core's multiple collection Include warning. Then I pick the fix: project only what the screen needs (often aggregates instead of collections), use AsSplitQuery() when I really need the full entities, or load the collections separately. The trade-off: split queries mean more round trips and no consistent snapshot unless you add a transaction.

🗣 Full answer (senior)

How I would answer this in an interview

"When you Include several collections in one EF Core query, EF Core by default generates one SQL statement with a LEFT JOIN per collection. Joining a parent to two sibling collections gives you every combination of the children, so the row count is the product, not the sum. Fifty orders with twenty lines, ten notes and thirty status events comes back as three hundred thousand rows, and every row repeats the order columns, including any big text columns. SQL Server sorts and streams all that, the network carries it, and EF Core has to read every row and throw away the duplicates during identity resolution.

To confirm it, I first print the SQL with ToQueryString() and look for multiple LEFT JOINs to collection tables, plus the ORDER BY on all the keys that EF Core needs to stitch the results. Then I run it with the actual execution plan or SET STATISTICS IO, TIME ON and compare the rows returned to the number of entities I expect. EF Core also logs a warning, MultipleCollectionIncludeWarning, when a query loads more than one collection without a splitting behaviour configured, so I check the logs for that.

The fix depends on what the endpoint needs. Most of the time the screen doesn't need all the children: it needs the last status and a count of lines, so a projection with Count() and a subquery is the best answer. If I really need the full graph, for example to modify the aggregate, AsSplitQuery() sends one query per collection, so the rows add up instead of multiplying. The mistake I see is turning on split queries globally and forgetting they aren't a consistent snapshot. Split queries trade one huge result for several round trips, so I choose them deliberately, query by query."


Why the rows multiply

Query shape Rows returned for 50 orders (20 lines, 10 notes, 30 events each)
Orders only 50
Include(Lines) 1,000
Include(Lines).Include(Notes) 10,000
Include(Lines).Include(Notes).Include(Events) 300,000
Same with AsSplitQuery() 50 + 1,000 + 500 + 1,500 = 3,050 across 4 queries

Reference navigations (Include(o => o.Customer)) don't multiply because they add at most one row per parent. Only collections do, and only sibling collections multiply each other; a chain (Lines then Product) grows with the leaf count.

Choosing the fix

Option When it fits Watch out for
Projection with Select Read endpoints; screens need counts, latest items or a few columns Not tracked, so not for updates
AsSplitQuery() You need full entities from several collections One round trip per collection; data can change between them
UseQuerySplittingBehavior(SplitQuery) globally Most queries load several collections Applies to everything; use AsSingleQuery() where consistency matters
Separate explicit loads The graph depends on conditions, or one collection is huge More code; needs a tracked parent or a Contains query
Filtered Include (Include(o => o.Events.OrderByDescending(e => e.At).Take(5))) You only need a few children Still multiplies if combined with other collections

Production example

A case-management screen [in a system I worked on] loaded cases with notes, attachments and history in one query. For 25 cases SQL Server returned about 400,000 rows and the call took 6 to 8 seconds. Projecting counts and the latest five history items brought it to one query of 25 rows plus a split query for the history, and the call dropped to about 150 ms.

🔍 What the interviewer is checking

Checks that the candidate understands the row multiplication behind collection Includes, can prove it with evidence, and picks a fix based on the use case rather than a global switch.

Green flags

  • Explains product versus sum of child rows, and that reference navigations do not multiply
  • Confirms with ToQueryString, actual rows in the plan or STATISTICS IO, and the EF Core warning
  • Prefers projection for reads
  • Knows split queries lose snapshot consistency and need a unique order for paging

Red flags

  • Thinks AsSplitQuery() is free or always better
  • Blames SQL Server and adds indexes without looking at row counts
  • Cannot explain why the duplicated parent columns matter

📚 Learn in depth

1. What the single query looks like

For db.Orders.Include(o => o.Lines).Include(o => o.Notes) EF Core generates roughly:

SELECT [o].[Id], [o].[CustomerId], [o].[Comments],
       [l].[Id], [l].[OrderId], [l].[Sku], [l].[Quantity],
       [n].[Id], [n].[OrderId], [n].[Text]
FROM [Orders] AS [o]
LEFT JOIN [OrderLines] AS [l] ON [o].[Id] = [l].[OrderId]
LEFT JOIN [OrderNotes] AS [n] ON [o].[Id] = [n].[OrderId]
WHERE [o].[CustomerId] = @customerId
ORDER BY [o].[Id], [l].[Id]

The two joins are independent, so for each order SQL Server produces lines x notes rows. The ORDER BY lets EF Core detect when a new parent starts while it streams the reader.

2. Where the cost goes

SQL Server             network            EF Core
──────────             ───────            ───────
join + sort       ->   300k rows    ->    read every row
(tempdb spills          x width            look up keys in the
 if the sort is big)    (parent cols       identity map, discard
                        repeated)          duplicates, build graph

The width matters as much as the count: an nvarchar(max) comment column on the order is repeated 6,000 times per order. Memory grants for the sort can also spill to tempdb, which shows up as a warning in the actual plan.

3. How split queries work

With AsSplitQuery() EF Core sends the root query and then one query per collection, each joined back to the root filter:

SELECT [o].[Id], [o].[CustomerId], [o].[Comments] FROM [Orders] AS [o]
WHERE [o].[CustomerId] = @customerId ORDER BY [o].[Id];

SELECT [l].[Id], [l].[OrderId], [l].[Sku], [l].[Quantity], [o].[Id]
FROM [Orders] AS [o] INNER JOIN [OrderLines] AS [l] ON [o].[Id] = [l].[OrderId]
WHERE [o].[CustomerId] = @customerId ORDER BY [o].[Id];

The root filter runs again for each collection, so an expensive root predicate is paid several times. Without a transaction at snapshot or serializable isolation, rows can change between the queries. With Skip/Take you need a deterministic OrderBy with a unique key, or the pages of the different queries may not line up.

4. Confirming it

  • ToQueryString() shows the joins.
  • The actual execution plan shows actual rows on the final operator; SET STATISTICS IO ON shows logical reads.
  • Application Insights shows a long single SQL dependency, not many short ones (the opposite of N+1).
  • EF Core logs RelationalEventId.MultipleCollectionIncludeWarning when a single query loads several collections and no splitting behaviour is configured.

5. Why projection usually wins

Screens rarely need every child row. Select(o => new { o.Id, LineCount = o.Lines.Count(), LastNote = o.Notes.OrderByDescending(n => n.At).Select(n => n.Text).FirstOrDefault() }) becomes correlated subqueries or OUTER APPLY, returning exactly one row per order.

Try it yourself

  1. Seed 50 orders with 20 lines, 10 notes and 30 events each, run the three-Include query and record the rows returned with SET STATISTICS IO, TIME ON.
  2. Add AsSplitQuery() and compare duration and total rows with BenchmarkDotNet.
  3. Configure logging and find the MultipleCollectionIncludeWarning entry.
  4. Rewrite the query as a projection with counts and the latest note and compare the plan.
  5. Add Skip/Take to the split query without OrderBy and see the EF Core warning about row limiting without ordering.

💻 Code

The exploding query, then the two fixes: projection for reads and a split query when the full graph is needed.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;

public sealed record OrderCard(int Id, string CustomerName, int LineCount, string? LatestNote, DateTime? LastEventAt);

public sealed class OrderReads(ShopDbContext db)
{
    // BAD: three sibling collections in one query -> rows = orders x lines x notes x events.
    public Task<List<Order>> LoadExplodingAsync(int customerId, CancellationToken ct) =>
        db.Orders
            .Where(o => o.CustomerId == customerId)
            .Include(o => o.Lines)
            .Include(o => o.Notes)
            .Include(o => o.Events)
            .ToListAsync(ct);

    // BEST for a read screen: one row per order, only what the UI shows.
    public Task<List<OrderCard>> GetCardsAsync(int customerId, CancellationToken ct) =>
        db.Orders
            .Where(o => o.CustomerId == customerId)
            .OrderBy(o => o.Id)
            .Select(o => new OrderCard(
                o.Id,
                o.Customer.Name,
                o.Lines.Count,
                o.Notes.OrderByDescending(n => n.CreatedAt).Select(n => n.Text).FirstOrDefault(),
                o.Events.Max(e => (DateTime?)e.At)))
            .ToListAsync(ct);

    // When the aggregate must be loaded to change it: one query per collection.
    public Task<List<Order>> LoadForUpdateAsync(int customerId, CancellationToken ct) =>
        db.Orders
            .Where(o => o.CustomerId == customerId)
            .OrderBy(o => o.Id)                 // deterministic order keeps split queries aligned
            .Include(o => o.Lines)
            .Include(o => o.Notes)
            .Include(o => o.Events)
            .AsSplitQuery()
            .ToListAsync(ct);
}
// Program.cs: make the default explicit and surface the warning as an error in development.
builder.Services.AddDbContext<ShopDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("Shop"),
        sql => sql.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery));

    if (builder.Environment.IsDevelopment())
    {
        options.ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning));
    }
});

⚠ Common mistakes

  • Mistake: Treating three Includes as three times the data. Why it is wrong: sibling collections multiply, so the rows are the product of the child counts. Instead: estimate parent x child A x child B before writing the query.
  • Mistake: Turning on SplitQuery globally and forgetting about consistency. Why it is wrong: the collection queries run separately and can see data changed in between. Instead: choose it per query, or wrap the read in a snapshot transaction when consistency matters.
  • Mistake: Using split queries with Skip/Take but no unique OrderBy. Why it is wrong: each query may page differently, so children attach to the wrong set of parents or go missing. Instead: order by a unique key before paging.
  • Mistake: Including whole collections to show a count or the latest item. Why it is wrong: it transfers every child row to compute one number. Instead: project Count() or a FirstOrDefault() subquery.
  • Mistake: Ignoring wide parent columns. Why it is wrong: a large text column on the parent is repeated on every joined row. Instead: project it out or move it to a separate table or query.
  • Mistake: Diagnosing it from duration alone. Why it is wrong: a slow query could also be a missing index or a bad plan. Instead: compare actual rows returned to the entity count.

🏛 Senior insight: trade-offs

Cartesian explosion is the mirror image of N+1: one query that is too big instead of many that are too small. Both come from loading entity graphs when the use case wanted a shape. My default for reads is projection, and I reserve Include for loading aggregates I intend to change, where I keep the aggregate small enough that a split query or a single collection is enough. I make the EF Core warning throw in development so nobody ships a multi-collection single query by accident.

In plain terms: cartesian explosion means the database returns every combination of child rows, and snapshot consistency means all the rows you read come from the same moment in time. A single query gives you consistency but explodes; split queries avoid the explosion but each round trip can see a slightly different database unless you wrap them in a snapshot transaction.

Option When it fits Cost When not to
Single query (default) One collection, or small children One round trip, rows multiply Two or more sibling collections
AsSplitQuery() Full graph of several collections, e.g. loading an order to edit its lines and notes 1 + one round trip per collection (fixed, not per row), root filter repeated, no snapshot Need a consistent snapshot without a transaction; high-latency links where round trips dominate
Projection Read screens and APIs, e.g. a list showing counts and the latest status Least data Updating the entities
Separate loads Conditional or very large collections, e.g. load attachments only when the user opens a tab More code, extra round trips Simple fixed graphs

How I measure the fix

Measure Tool What good looks like
Rows returned and logical reads SET STATISTICS IO, TIME ON, actual execution plan Rows close to the entity count; reads drop by an order of magnitude
Reading the plan Actual plan in SSMS or Azure Data Studio: compare Actual Number of Rows with Estimated on the join and sort operators, look for sort spill and memory grant warnings No spill warning; actual rows small on the final operator
End-to-end duration BenchmarkDotNet locally; Application Insights dependency duration in production p95 down, and the number of SQL dependencies per request stays small (split adds a few, not N)
Client cost BenchmarkDotNet MemoryDiagnoser, dotnet-counters allocation rate Allocations per request drop with the row count

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions AsSplitQuery() Why: Checks the detail of what split queries change in the SQL and their consistency trade-offs
    How to answer

    Cartesian explosion happens when one query Includes two or more sibling collections: SQL returns one row per combination, so an order with 50 lines and 20 payments becomes 1,000 rows, each repeating the order's columns. EF Core logs a warning when it sees this.

    AsSplitQuery() makes EF Core send one root query plus one query per collection Include (orders; then lines joined to the same filtered orders; then payments) and stitch the results together in memory. For that order, rows transferred become 1 (root) + 50 (lines) + 20 (payments) = 71 instead of 1,000.

    The trade-offs: an extra round trip per collection (it adds up with network latency), and the statements are not one consistent snapshot unless you wrap them in a transaction with snapshot isolation. Often the better answer is a projection that loads only what's needed.

  2. When: Candidate suggests projecting into a DTO instead of Include Why: Checks they know the SQL and tracking difference between Include and Select
    How to 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.

  3. When: Candidate mentions that split queries can see data change between round trips Why: Checks they can combine split queries with a transaction and the right isolation level, and know the cost
    How to answer

    Wrap the split query in a transaction: await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Snapshot, ct); then run the query and commit. Every split statement then reads the same committed row versions without blocking writers. Snapshot isolation must be allowed on the database (ALTER DATABASE ... SET ALLOW_SNAPSHOT_ISOLATION ON; Azure SQL enables it by default); turning it on adds row versioning for all writes, so test the tempdb / version store impact. Serializable also gives consistency but takes range locks and blocks writers. Keep the transaction short. If a single projected query can return what you need, it is consistent by itself and avoids the problem.

🛠 Real-world problems: how you handle them

Case screen returning 400,000 rows for 25 cases
Situation
A case-management system on ASP.NET Core and EF Core with Azure SQL [Business Critical tier]. The case list loaded each case with notes, attachments metadata and history for [about 300 internal users].
Signals
The list page took 6 to 8 seconds; Application Insights showed one long SQL dependency per request (not many short ones); Azure SQL showed high tempdb use and memory grant waits; users reported timeouts at [9 am].
Investigation
Printed the query with `ToQueryString()` and saw three LEFT JOINs to collection tables ordered by all keys. Ran it in SSMS with the actual plan: about 400,000 actual rows from the final operator for 25 cases, a sort spilling to tempdb, and a wide `nvarchar(max)` description repeated on every row. EF Core logs showed `MultipleCollectionIncludeWarning`.
Resolution
Immediately: added `AsSplitQuery()` to the query, which dropped the call to about 900 ms. Then rewrote the list as a projection with note and attachment counts and the latest five history items, leaving full Includes only on the case detail page.
Prevention
Configured `MultipleCollectionIncludeWarning` to throw in development and CI; added a performance test asserting the list query returns one row per case; documented in an ADR that list endpoints project into DTOs.

How to tell it (STAR)

**S:** Our case list in [the case-management system] took 6 to 8 seconds and timed out for some users every morning. **T:** I owned the fix because I [had built the original screen / was on support that sprint]. **A:** Application Insights showed one long SQL call rather than many short ones, which pointed away from N+1. I printed the SQL with ToQueryString and saw three collection joins; the actual plan showed about 400,000 rows for 25 cases and a sort spilling to tempdb. I added AsSplitQuery as a quick mitigation, then rewrote the list as a projection with counts and the latest history items, and made EF Core's multiple-collection warning throw in development. **R:** The list now returns in about [150 ms], the tempdb spills stopped, and the warning has stopped [two] similar queries from reaching production.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me