📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you load related data in EF Core? Explain eager loading with Include and ThenInclude, explicit loading, and lazy loading, when you would use each, and what filtered Include lets you do.

Covers EF Core's three ways to load navigations (eager with Include/ThenInclude, explicit with Entry().Collection().Load, lazy with proxies), filtered Include, the SQL each produces and when to choose each.

Junior Theory Intermediate eager-loading ef-core explicit-loading include lazy-loading querying

🎯 Key points

  • Navigations are not loaded by default: null or empty unless you ask (or fix-up links tracked entities)
  • Include/ThenInclude: eager, one query with JOINs (or split queries)
  • Several collection Includes in one query cause cartesian explosion; AsSplitQuery() or projection
  • Explicit: Entry(x).Collection(...).LoadAsync(), or Query() to filter/count
  • Lazy: UseLazyLoadingProxies + virtual navigations on non-sealed classes; not Native AOT/trimming friendly
  • Filtered Include (EF Core 5+): Where, OrderBy, Skip, Take inside Include
  • Lazy loading causes N+1 and fails after the context is disposed
  • For read endpoints, projection with Select often beats Include

⏱ 30-second answer

EF Core does not load navigation properties unless you ask. There are three ways:

  • Eager loading: Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().
  • Explicit loading: await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.
  • Lazy loading: with UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.

Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).

The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.

🗣 Full answer (senior)

How I would answer this in an interview

"By default EF Core loads only the entity you queried. A reference navigation like order.Customer stays null and a collection like order.Lines stays empty unless I load it, or unless those entities are already tracked by the same context, in which case fix-up fills them in.

The default I reach for is eager loading with Include and ThenInclude. db.Orders.Include(o => o.Lines).ThenInclude(l => l.Product) produces one SQL statement with LEFT JOINs and an ORDER BY on the keys, so EF Core can stitch the rows back into objects. Since EF Core 5 I can filter inside it: Include(c => c.Orders.Where(o => o.Status == Open).Take(5)). Explicit loading is for when I already have the entity and only sometimes need a navigation: await db.Entry(order).Collection(o => o.Lines).LoadAsync(ct). Its Query() method is handy because I can count or filter related rows without loading them all. Lazy loading needs the proxies package, UseLazyLoadingProxies() and virtual navigations. Touching the property runs a query.

The mistake I see is lazy loading in web APIs. A loop over 50 orders that touches order.Customer runs 51 queries, and a JSON serialiser walking navigations can fire dozens more or hit a cycle. So I leave lazy loading off, use Include when I need entities to update, and for read endpoints I usually skip Include altogether and project to a DTO with Select, which loads exactly the columns I need."


The three strategies

Strategy How Queries Best for
Eager Include / ThenInclude 1 (or N with AsSplitQuery) You know up front you need it
Explicit Entry(e).Collection(...).LoadAsync() / .Reference(...) 1 per load call Conditional loading of an already-loaded entity
Lazy Proxies + virtual 1 per navigation access Desktop apps or scripts with a long-lived context; rarely APIs

Filtered Include

Allowed inside Include Example
Where Include(c => c.Orders.Where(o => o.IsOpen))
OrderBy / ThenBy .OrderByDescending(o => o.PlacedAt)
Skip / Take .Take(5)

One caveat: if the related entities are already tracked, fix-up can add them to the collection even though the filter excluded them. Use a fresh context or AsNoTracking() when exact contents matter.

When not to use Include

Situation Better choice
Read-only API response Select into a DTO
Several collection Includes on big tables AsSplitQuery() or projection
You only need a count o.Lines.Count() in a projection

Production example

An order history page used lazy loading and rendered 20 orders with their customer and lines: [41] queries and [~600 ms] per page under load. Switching to one Select projection with the needed fields made it [one query, ~35 ms].

🔍 What the interviewer is checking

Checks that the candidate knows navigations are not loaded by default and can pick the right loading strategy.

Green flags

  • Names all three strategies with the correct APIs.
  • Mentions filtered Include and its options.
  • Warns about lazy loading and N+1 in APIs.
  • Suggests projection for read-only data.

Red flags

  • Thinks EF Core loads everything automatically.
  • Recommends lazy loading as a default.
  • Uses Include for every navigation on every query.

📚 Learn in depth

1. Why navigations start empty

EF Core materialises only the columns in the SQL it ran. A navigation is filled when (a) you load it, or (b) fix-up links it to an entity already tracked by the same context. That second rule surprises people: a navigation can appear "loaded" just because an earlier query in the same request tracked the related row.

2. Eager loading SQL

db.Orders.Include(o => o.Customer).Include(o => o.Lines).ThenInclude(l => l.Product)
SELECT [o].[Id], ..., [c].[Id], ..., [s].[Id], ..., [s].[ProductId0], ...
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
LEFT JOIN (
    SELECT [l].*, [p].[Id] AS [ProductId0], [p].[Name]
    FROM [OrderLines] AS [l]
    INNER JOIN [Products] AS [p] ON [l].[ProductId] = [p].[Id]
) AS [s] ON [o].[Id] = [s].[OrderId]
ORDER BY [o].[Id], [c].[Id], [s].[Id]

Reference navigations add columns; collection navigations multiply rows (one per line). Two sibling collection Includes multiply again (cartesian explosion); AsSplitQuery() sends one query per collection instead.

3. Explicit loading

Entry(order)
  ├ .Reference(o => o.Customer).LoadAsync()
  ├ .Collection(o => o.Lines).LoadAsync()
  └ .Collection(o => o.Lines).Query()      -> IQueryable<OrderLine>
         .Where(l => l.Quantity > 10).CountAsync()   (no entities loaded)

IsLoaded tells you whether a navigation has been loaded, so you can avoid reloading it.

4. Lazy loading internals

UseLazyLoadingProxies()
  └ EF Core generates (Castle) proxy subclasses of your entities at runtime
      └ overrides virtual navigation getters:
           get { loader.Load(this, nameof(Lines)); return base.Lines; }

Requirements: Microsoft.EntityFrameworkCore.Proxies, public or protected virtual navigations, non-sealed classes. Alternative without proxies: inject ILazyLoader into the entity. Both need a live context; after disposal you get an exception. Runtime proxy generation is not compatible with Native AOT or trimming.

5. Choosing

Need to update the graph?            -> Include (tracked)
Read-only, response DTO?             -> Select projection
Need related data only sometimes?    -> Explicit loading or a second query
Long-lived context in a desktop app? -> Lazy loading is acceptable

Try it yourself

  1. Query an order without Include, check order.Lines.Count and explain why it is 0.
  2. Add Include(...).ThenInclude(...) and read the SQL with ToQueryString().
  3. Turn on lazy loading, loop over 20 orders touching Customer.Name, and count the commands in the log.
  4. Use Entry(order).Collection(o => o.Lines).Query().CountAsync() and confirm no lines are materialised.
  5. Write a filtered Include with Take(3) and inspect the ROW_NUMBER() SQL it generates.

💻 Code

The three loading strategies and filtered Include.

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed class OrderLoading(ShopDbContext db)
{
    // Eager: one query, used when we will modify the graph.
    public Task<Order?> GetForEditAsync(int id, CancellationToken ct) =>
        db.Orders
          .Include(o => o.Customer)
          .Include(o => o.Lines).ThenInclude(l => l.Product)
          .SingleOrDefaultAsync(o => o.Id == id, ct);

    // Filtered Include: only the five most recent open orders per customer.
    public Task<List<Customer>> GetWithRecentOpenOrdersAsync(CancellationToken ct) =>
        db.Customers
          .AsNoTracking()   // avoids fix-up adding other tracked orders to the collection
          .Include(c => c.Orders
              .Where(o => o.Status == OrderStatus.Open)
              .OrderByDescending(o => o.PlacedAt)
              .Take(5))
          .ToListAsync(ct);

    // Explicit: load lines only when the caller needs them.
    public async Task EnsureLinesAsync(Order order, CancellationToken ct)
    {
        var lines = db.Entry(order).Collection(o => o.Lines);
        if (!lines.IsLoaded)
            await lines.LoadAsync(ct);
    }

    // Explicit Query(): count related rows without loading them.
    public Task<int> CountBigLinesAsync(Order order, CancellationToken ct) =>
        db.Entry(order).Collection(o => o.Lines).Query()
          .Where(l => l.Quantity > 10)
          .CountAsync(ct);
}
// Lazy loading (shown for completeness; usually off in web APIs).
builder.Services.AddDbContext<ShopDbContext>(o => o
    .UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
    .UseLazyLoadingProxies());   // needs Microsoft.EntityFrameworkCore.Proxies

public class Order
{
    public int Id { get; set; }
    public virtual Customer Customer { get; set; } = null!;          // virtual: proxy can override
    public virtual ICollection<OrderLine> Lines { get; set; } = [];
}

⚠ Common mistakes

  • Mistake: Expecting navigations to be populated automatically. Why it is wrong: EF Core loads only what the SQL selected, so order.Lines is empty. Instead: Include it, load it explicitly, or project it.
  • Mistake: Turning on lazy loading in a web API. Why it is wrong: loops and JSON serialisation trigger N+1 queries and cycles, and runtime proxies don't work with Native AOT or trimming. Instead: keep it off; use Include or projection.
  • Mistake: Including every navigation "just in case". Why it is wrong: each collection Include multiplies rows and columns transferred. Instead: include only what the use case needs, or project.
  • Mistake: Including two or more sibling collections in one query (Include(o => o.Lines).Include(o => o.Payments)). Why it is wrong: the single SQL query returns lines × payments rows per order (cartesian explosion); 50 lines and 20 payments become 1,000 rows. EF Core logs a warning about this. Instead: use AsSplitQuery() or project only what you need.
  • Mistake: Trusting a filtered Include on a tracking query. Why it is wrong: fix-up can add already-tracked entities that the filter excluded. Instead: use AsNoTracking() or a fresh context.
  • Mistake: Repeating Include for each level instead of ThenInclude. Why it is wrong: it works but is noisy and easy to get wrong for collections of collections. Instead: chain ThenInclude for deeper levels.
  • Mistake: Accessing a lazy navigation after the context is disposed. Why it is wrong: it throws, typically during serialisation after the request scope ended. Instead: load what you need inside the unit of work.

🏛 Senior insight: trade-offs

I pick the loading strategy by the use case: commands that modify a graph get tracked Include; queries that feed a response get a Select projection. Lazy loading is a convenience for long-lived contexts, and in a request/response API it mostly turns into hidden latency.

Option When it fits Cost When not to
Include Loading an aggregate to change it Wide rows, possible cartesian explosion Read-only responses
Explicit loading Conditional, after the main load Extra round trip per call In a loop over many entities
Lazy loading Desktop or scripting with a long-lived context N+1, AOT-incompatible proxies Web APIs, serialisation
Select projection Read endpoints Need a DTO type When you must track and update entities

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is unsure how a LINQ query becomes SQL. Why: Checks the EF Core basics behind loading.
    How to answer

    Entity Framework Core is Microsoft's object-relational mapper (ORM): you write C# classes (entities) and LINQ, and EF Core produces the SQL, runs it and turns the rows back into objects.

    • DbContext is a session with the database: it owns the connection, the change tracker and SaveChanges(), which writes all pending changes in one transaction. In ASP.NET Core it is scoped to the request.
    • DbSet is the entry point for querying and adding one entity type; it implements IQueryable<T>.
    • A LINQ query is captured as an expression tree, translated by the SQL Server provider into parameterised SQL, and executed only when you enumerate it (ToListAsync).

    The trade-off: EF Core buys productivity, migrations and type safety; Dapper or ADO.NET buy you full control of the SQL for hot paths.

  2. When: Candidate mentions lazy loading proxies being turned on in a project. Why: Checks they can review a configuration that enables lazy loading by default.
    How to answer

    I rank findings by severity:

    1. Connection string in OnConfiguring: a secret in source control and configuration that can't change per environment. Move it to configuration (user secrets locally, Key Vault or Entra ID managed identity in Azure) and register with AddDbContext.
    2. Cascade delete everywhere: one delete can wipe thousands of rows; use Restrict for business data.
    3. Lazy loading proxies: hidden N+1 queries and serialisation cycles in an API; use Include or projection.
    4. Guid.NewGuid() clustered keys: page splits and fragmentation; let EF Core generate sequential GUIDs or make the PK nonclustered.
    5. Unconfigured strings: nvarchar(max), which can't be an index key.

    Then I fix it systemically with ConfigureConventions defaults and a migration checklist. The trade-off: defaults are fast to write, but each one here costs security, data or performance later.

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me