What is AsSplitQuery in EF Core?
Quick Answer
When you Include more than one collection navigation, EF Core's default single-query mode produces a cartesian product — rows = parents × collection1 × collection2 — which duplicates data massively. AsSplitQuery() runs one query per collection instead, joining the results in memory. Fewer bytes over the wire, but multiple round trips.
If I Include two or more collections on the same entity, EF's default behaviour is one big query with joins, and that creates a cartesian product — a customer with ten orders and five addresses comes back as fifty rows with everything duplicated. AsSplitQuery tells EF to run a separate query for each collection and stitch them together in memory, so there's no duplication, at the cost of extra round trips. The one thing to be aware of is that the separate queries aren't automatically a consistent snapshot, so wrap them in a transaction if that matters.
- Single query: one SQL statement, one round trip, but a
Customerwith 10 orders and 10 addresses returns 100 rows. - Split query: a query for customers, a query for their orders, a query for their addresses — no duplication, 3 round trips.
- Set globally:
options.UseSqlServer(cs, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)), or per query. - Caveat: split queries aren't a single transaction snapshot unless you wrap them — data could change between the sub-queries.