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.
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.
"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 orSET STATISTICS IO, TIME ONand 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."
| 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.
| 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 |
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.
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
ToQueryString, actual rows in the plan or STATISTICS IO, and the EF Core warningRed flags
AsSplitQuery() is free or always betterFor 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.
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.
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.
ToQueryString() shows the joins.SET STATISTICS IO ON shows logical reads.RelationalEventId.MultipleCollectionIncludeWarning when a single query loads several collections and no splitting behaviour is configured.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.
SET STATISTICS IO, TIME ON.AsSplitQuery() and compare duration and total rows with BenchmarkDotNet.MultipleCollectionIncludeWarning entry.Skip/Take to the split query without OrderBy and see the EF Core warning about row limiting without ordering.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));
}
});
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.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.Count() or a FirstOrDefault() subquery.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.