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.
EF Core does not load navigation properties unless you ask. There are three ways:
Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.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.
"By default EF Core loads only the entity you queried. A reference navigation like
order.Customerstaysnulland a collection likeorder.Linesstays 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
IncludeandThenInclude.db.Orders.Include(o => o.Lines).ThenInclude(l => l.Product)produces one SQL statement withLEFT JOINs and anORDER BYon 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). ItsQuery()method is handy because I can count or filter related rows without loading them all. Lazy loading needs the proxies package,UseLazyLoadingProxies()andvirtualnavigations. Touching the property runs a query.The mistake I see is lazy loading in web APIs. A loop over 50 orders that touches
order.Customerruns 51 queries, and a JSON serialiser walking navigations can fire dozens more or hit a cycle. So I leave lazy loading off, useIncludewhen I need entities to update, and for read endpoints I usually skipIncludealtogether and project to a DTO withSelect, which loads exactly the columns I need."
| 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 |
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.
| 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 |
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].
Checks that the candidate knows navigations are not loaded by default and can pick the right loading strategy.
Green flags
Red flags
Include for every navigation on every query.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.
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.
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.
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.
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
Include, check order.Lines.Count and explain why it is 0.Include(...).ThenInclude(...) and read the SQL with ToQueryString().Customer.Name, and count the commands in the log.Entry(order).Collection(o => o.Lines).Query().CountAsync() and confirm no lines are materialised.Take(3) and inspect the ROW_NUMBER() SQL it generates.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; } = [];
}
order.Lines is empty. Instead: Include it, load it explicitly, or project it.Include or projection.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.AsNoTracking() or a fresh context.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.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 |
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.
SaveChanges(), which writes all pending changes in one transaction. In ASP.NET Core it is scoped to the request.IQueryable<T>.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.
I rank findings by severity:
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.Restrict for business data.Include or projection.Guid.NewGuid() clustered keys: page splits and fragmentation; let EF Core generate sequential GUIDs or make the PK nonclustered.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.
Last updated 23 Nov 2026.