Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    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.
    • Include loads 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.
    • DbContext is not thread-safe: one operation at a time per context.

    Loading strategies

    StrategyHowSQL commandsUse whenRisk
    EagerInclude(b => b.Posts), ThenInclude(...)1, or 1 + 1 per collection when splityou know you need the related datarepeated rows with several collection includes
    Explicitdb.Entry(blog).Collection(b => b.Posts).LoadAsync()1 per load of a navigation not yet loadedloading depends on a conditionN+1 when called in a loop
    LazyUseLazyLoadingProxies() (Microsoft.EntityFrameworkCore.Proxies) and virtual navigations1 each time an unloaded navigation is touchedrarely: only with tight control of the context's lifetimehidden N+1, synchronous I/O, serializers walking the graph
    ProjectionSelect(b => new { b.Name, Count = b.Posts.Count })1read models and API responsesthe 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:

    ShapeCommands
    Explicit load per blog in a loop4 (1 for the blogs + 3 loads)
    Include, single query1
    Include with AsSplitQuery()2
    Projection with a post count1

    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

    C#
    // 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
    Howthe default.AsSplitQuery(), or UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) for all queries
    SQLone statement with JOINsone statement for the root, one per collection include
    Good atone round trip, one statement (how consistent it is depends on the database and isolation level)avoiding repeated parent columns for every child row
    Weak atsibling collection includes multiply the rowsmore 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 SaveChangesyesnono
    One instance per entity keyyesno: duplicates possible across includesyes, within that query
    Use forload, change, saveread-only queriesread-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 in db.Orders.ToList().Where(...), filters in memory after loading every row.
    • Find and FindAsync look in the change tracker before querying; FirstOrDefault always queries.
    • Compiled queries (EF.CompileAsyncQuery) skip the query-cache lookup on hot paths; they do not fix a bad query shape.
    • One DbContext per unit of work (scoped in ASP.NET Core), or IDbContextFactory<T> for work outside a request.

    Common mistakes

    • Several collection Includes in one query: rows multiply; use AsSplitQuery() 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() then Update(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?

    A 1
    B 3
    C 4
    D 7
    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?

    A It loads the collections lazily later
    B It sends one statement for the blogs and one per collection
    C It turns off tracking for the collections
    D It makes the statements one consistent read
    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?

    A db.Blogs.AsNoTracking().ToList()
    B db.Blogs.Select(b => new { b.Name }).ToList()
    C db.Blogs.Select(b => new { Blog = b, b.Name }).ToList()
    D A query on a keyless entity type
    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

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·