EF Core Loading Cheat Sheet: Eager, Lazy, Explicit, Split Queries and AsNoTracking
Compare eager, explicit and lazy loading.
How EF Core loads related data (eager, explicit, lazy or by projection), how many SQL commands each costs, and how tracking and split queries change the picture.
At a glance
- Every loading choice answers two questions: when the related data is fetched, and how many round trips it costs.
- N+1: one query for the parents, then one per parent. It appears with explicit loads in a loop and with lazy loading.
Includeloads related data up front in one query;AsSplitQuery()sends one query for the root plus one per included collection, which avoids repeated rows.- A projection (
Select) to the fields an endpoint returns is usually the best read shape for an API; a projection of plain values creates no entities, so nothing is tracked. - Tracking is a separate choice:
AsNoTracking()for read-only queries, tracking for load, change, save. DbContextis not thread-safe: one operation at a time per context.
Loading strategies
| Strategy | How | SQL commands | Use when | Risk |
|---|---|---|---|---|
| Eager | Include(b => b.Posts), ThenInclude(...) | 1, or 1 + 1 per collection when split | you know you need the related data | repeated rows with several collection includes |
| Explicit | db.Entry(blog).Collection(b => b.Posts).LoadAsync() | 1 per load of a navigation not yet loaded | loading depends on a condition | N+1 when called in a loop |
| Lazy | UseLazyLoadingProxies() (Microsoft.EntityFrameworkCore.Proxies) and virtual navigations | 1 each time an unloaded navigation is touched | rarely: only with tight control of the context's lifetime | hidden N+1, synchronous I/O, serializers walking the graph |
| Projection | Select(b => new { b.Name, Count = b.Posts.Count }) | 1 | read models and API responses | the query still needs to translate and stay small |
Three blogs with two posts each, measured with EF Core 10.0.12 on SQLite, counting reader commands:
| Shape | Commands |
|---|---|
| Explicit load per blog in a loop | 4 (1 for the blogs + 3 loads) |
Include, single query | 1 |
Include with AsSplitQuery() | 2 |
| Projection with a post count | 1 |
With N blogs, the loop costs N + 1 commands; the others stay at the same count while rows and memory still grow with the data.
N+1, and two fixes
// N+1: one query for the orders, then one per order
var orders = await db.Orders.ToListAsync(ct);
foreach (var o in orders)
await db.Entry(o).Collection(x => x.Lines).LoadAsync(ct);
// Fix A: eager loading
var withLines = await db.Orders.Include(o => o.Lines).ToListAsync(ct);
// Fix B: project only what the endpoint returns
var summaries = await db.Orders
.Select(o => new { o.Id, LineCount = o.Lines.Count, Total = o.Lines.Sum(l => l.Price * l.Qty) })
.ToListAsync(ct);To detect N+1: log SQL (LogTo(Console.WriteLine) or the Microsoft.EntityFrameworkCore.Database.Command category), count commands per request in a test with a DbCommandInterceptor, or look at the database spans in traces.
Single or split query?
| Single query (default) | Split query | |
|---|---|---|
| How | the default | .AsSplitQuery(), or UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) for all queries |
| SQL | one statement with JOINs | one statement for the root, one per collection include |
| Good at | one round trip, one statement (how consistent it is depends on the database and isolation level) | avoiding repeated parent columns for every child row |
| Weak at | sibling collection includes multiply the rows | more round trips; no consistency between the statements unless you use a serializable or snapshot transaction |
EF Core logs a warning when a single query loads more than one collection navigation and no splitting behavior is configured. Before EF Core 10, split queries with Skip/Take needed a fully unique ordering, or pages could come back wrong.
Tracking or not?
| Tracking (default) | AsNoTracking() | AsNoTrackingWithIdentityResolution() | |
|---|---|---|---|
Detects changes for SaveChanges | yes | no | no |
| One instance per entity key | yes | no: duplicates possible across includes | yes, within that query |
| Use for | load, change, save | read-only queries | read-only graphs where duplicates would confuse |
In the same test, three blogs read with AsNoTracking() left 0 tracked entries; read again with tracking, 3. A projection that creates no entity instances is never tracked, but an entity inside a projection, such as new { Blog = b, b.Name }, is.
Other facts interviewers ask about
- Filtered include:
Include(b => b.Posts.Where(p => p.Published).OrderBy(p => p.Id).Take(5)). In a tracking query, posts already tracked can appear even if they fail the filter, and the navigation counts as loaded. - Since EF Core 3.0, client evaluation happens only in the final projection; a filter that cannot be translated throws instead of running in memory.
ToList()too early, as indb.Orders.ToList().Where(...), filters in memory after loading every row.FindandFindAsynclook in the change tracker before querying;FirstOrDefaultalways queries.- Compiled queries (
EF.CompileAsyncQuery) skip the query-cache lookup on hot paths; they do not fix a bad query shape. - One
DbContextper unit of work (scoped in ASP.NET Core), orIDbContextFactory<T>for work outside a request.
Common mistakes
- Several collection
Includes in one query: rows multiply; useAsSplitQuery()or a projection. - Lazy loading switched on "for convenience" in an API: a serializer can trigger a query per navigation.
- Tracking large read-only results: use
AsNoTracking()or a projection. AsNoTracking()thenUpdate(entity)on a whole graph: entities with key values are marked Modified, entities with unset generated keys are added, and two instances of one row conflict. Attach only what changed.- Running two queries at once on one context: await each one, or use separate contexts.
In an interview
What is the N+1 problem, and how do you fix it? One query loads N parents, then one more query runs for each parent's related data. Fix it with Include, or better for APIs, a projection that loads only the needed fields in one query.
When would you use a split query, and what do you give up? When several collection includes repeat parent rows many times. You give up the single round trip and the single consistent read.
Why is a projection often better than Include for an API? It reads only the columns the response needs, and a projection of plain values tracks nothing, so less data moves and less memory is used. The post-count projection above runs as one command.
What does AsNoTrackingWithIdentityResolution add? It returns one instance per entity key within the query, like tracking, but without keeping the entities in the change tracker.
Why is lazy loading risky in ASP.NET Core? Every touch of an unloaded navigation is a hidden query, often synchronous, and a serializer can walk the whole graph.
How do you prove an endpoint runs a bounded number of SQL commands? Count them in an integration test with a DbCommandInterceptor, and assert the count stays the same as the data grows.
Check yourself
Three blogs each have two posts, and no Posts collection is loaded yet. One query loads the blogs, then a loop calls Entry(blog).Collection(b => b.Posts).Load() for each blog. How many SQL commands run in all?
Show answer
Correct answer: C
One query loads the blogs, then one load runs per blog: 1 + 3 = 4.
Option A: 1 is the count for Include or the projection here; the loop adds one command per blog.
Option B: That forgets the query that loaded the blogs.
Option D: The loads are per blog, not per post.
A query includes two collection navigations of a blog. What does AsSplitQuery() change?
Show answer
Correct answer: B
A split query replaces the big JOIN with one statement for the root and one per collection, avoiding repeated rows.
Option A: Everything is still loaded up front by the same query call.
Option C: Tracking is a separate choice.
Option D: Separate statements are not consistent with each other unless a snapshot or serializable transaction makes them so.
Which read is tracked by the change tracker?
Show answer
Correct answer: C
The projection creates Blog entity instances, and a tracking query tracks them.
Option A: AsNoTracking turns tracking off.
Option B: A projection with no entity instances has nothing to track.
Option D: Keyless entity types are never tracked.
Sources
- Loading related data: eager, explicit and lazy loading.
- Eager loading:
Include,ThenInclude, filtered include and fixup. - Single vs. split queries: repeated rows, the warning, consistency, ordering before EF Core 10.
- Tracking vs. no-tracking queries:
AsNoTracking, identity resolution, projections. - Client vs. server evaluation: the EF Core 3.0 change.
- Lazy loading: proxies and virtual navigations.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·