How do you avoid N+1 queries and cartesian explosion when loading related data with Entity Framework Core?
Flipkart · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Entity Framework Core, SQL
Community answers
Posted by wasAsked editorial collection
N+1 occurs when one query loads parents and an additional query runs for each parent. Detect it through SQL logging/tracing and query counts, then shape the required data in one bounded query or a deliberate small set.
Example:
var orders = await db.Orders.AsNoTracking()
.Where(o => o.RestaurantId == tenant.RestaurantId && o.OutletId == tenant.OutletId)
.Select(o => new OrderDto(o.Id, o.Lines.Count, o.Lines.Sum(l => l.Total)))
.Take(100).ToListAsync(ct);
Blind Include chains can create cartesian explosions and huge payloads. Prefer projection; consider split queries for multiple collections and verify generated SQL. Disable accidental lazy loading in APIs when it hides database access. Add integration tests or telemetry for query count and latency.
Backbencher Developer · · 0 likes
N+1 queries happen when you load a list and then trigger one more query per item, typically via lazy loading:
var orders = await db.Orders.ToListAsync();
foreach (var o in orders)
Console.WriteLine(o.Customer.Name); // lazy loading: one query per order
Avoiding N+1:
- Eager loading with Include: db.Orders.Include(o => o.Customer) loads related data in the same query.
- Projection with Select (often best for APIs):
var rows = await db.Orders
.Select(o => new { o.Id, o.Total, CustomerName = o.Customer.Name })
.ToListAsync();
EF generates a single join and fetches only the needed columns.
- Disable or avoid lazy-loading proxies in web APIs, where they also cause problems during JSON serialization.
- Batch lookups: collect IDs and load related rows with one WHERE Id IN (...) query.
Cartesian explosion
When you Include several collection navigations in one query, the join multiplies rows:
db.Blogs.Include(b => b.Posts).Include(b => b.Contributors)
A blog with 100 posts and 50 contributors returns 5,000 rows, duplicating the blog columns each time.
Avoiding it:
- Split queries: add .AsSplitQuery() (or configure UseQuerySplittingBehavior globally) so EF runs one SQL query per collection and stitches the results together. Trade-off: several round trips, and without a transaction the data can be slightly inconsistent between queries.
- Project only what you need, or load collections separately with filtered includes (Include(b => b.Posts.Where(p => p.Published).Take(10))).
- Paginate: never Include unbounded collections in list endpoints.
How to detect problems:
- Enable EF logging (LogTo or the Microsoft.EntityFrameworkCore.Database.Command category) and count queries per request.
- EF Core warns about multiple collection includes without split-query configuration.
- Use AsNoTracking for read-only queries to reduce overhead.
- Profile with SQL Server Query Store, MiniProfiler or Application Insights dependency tracking.