Skip to the workspace
Pebellslearn by building
Object Relational Mapping  ›  Capstone Project

Lazy, Eager and Explicit Loading

Lazy, Eager, Explicit Loading 15 minRelated entities are not loaded automatically: eager loading fetches them with Include, explicit loading fetches them on request, and lazy loading fetches them on first access at the risk of many small queries.

aspnet core / Lazy, Eager and Explicit Loading

Explore each scene at your own pace.

01 · The rule

The rule

Lazy, Eager and Explicit Loading

ReadingRoom's members page loads members, then shows each member's loans. On your laptop with three members it is instant. In production with fifty it is slow, and the log shows fifty-one queries. The cause is how related data was loaded.

The rule

Related data is never free: include it, load it, or pay per access.

Member has a navigation property to its loans:

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Loan> Loans { get; set; } = [];
}

Loading db.Members does not fill Loans. You choose one of three strategies:

Eager — ask for it up front with Include:

var members = await db.Members
    .Include(m => m.Loans.Where(l => l.ReturnedAt == null))
    .ToListAsync();

Explicit — load it later, on purpose, for one entity:

var member = await db.Members.FindAsync(5);
await db.Entry(member!).Collection(m => m.Loans).LoadAsync();

Lazy — load it automatically the first time the property is read. It is off by default; you opt in with the Microsoft.EntityFrameworkCore.Proxies package, UseLazyLoadingProxies(), and virtual navigation properties.

Lazy loading is convenient and dangerous. A loop over 50 members that reads member.Loans fires one query for the members and then one per member: the N+1 problem. Each query is quick; together they are slow.

For multiple collections, Include can produce huge joined results; .AsSplitQuery() fetches each collection in its own query instead. And when a page only needs a few columns, a Select projection often beats loading whole entities.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.