What is the N+1 query problem, and how do you fix it in EF Core?
Quick Answer
N+1 is when you run 1 query to get a list of parents, then 1 more query per parent to load its children — 100 orders becomes 101 queries. Fixes: eager-load with Include, or better, project only what you need with Select so EF generates a single join query.
N+1 is the classic ORM performance bug: you fetch a list — say 50 customers — and then for each one you touch customer.Orders, which fires a separate query, so you've done 51 database round-trips for what should be one or two. In EF Core it usually comes from lazy loading inside a loop. The fix is to load the related data up front with Include, or, my preference, project straight to a DTO with Select so EF emits one join and only the columns I use. If I Include multiple collections I add AsSplitQuery to avoid the row explosion from the cartesian product.
- Cause is usually lazy loading triggered inside a
foreach, or calling a repository method per item. Includewith several collection includes can cause a cartesian explosion — useAsSplitQuery()to split into one query per include.- Projection (
Selectto a DTO) is often best: no tracking, only needed columns, one query. - Enable EF Core's
QueryLogging/ the analyzer that warns on multiple-collection includes; watch for repeated similar SQL in logs.