Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 41 ยท Relationships and Loading

Explicit Loading and Lazy Loading

Understand EF Core explicit loading with Entry().Collection().Load(), lazy loading with proxies and ILazyLoader, their hidden costs and when each one is the right tool, with runnable stand-ins.

Eager loading fetches related data in the same query. Sometimes you cannot know in advance whether you will need it: you have an entity in hand and a branch of your code decides, much later, that it wants the comments. EF Core offers two more strategies for that, explicit loading and lazy loading. They are about when the extra query runs, and who triggers it.

The EF Core code is read-only. The runnable blocks are stand-ins built from Lazy<T>, delegates and a query counter, because the real thing needs a provider.

Explicit loading

With explicit loading you call the load yourself, through the entity's Entry:

C#
var blog = await db.Blogs.FirstAsync(b => b.Id == 1);

// Collection navigation
await db.Entry(blog)
    .Collection(b => b.Posts)
    .LoadAsync();

// Reference navigation
var post = await db.Posts.FirstAsync();
await db.Entry(post)
    .Reference(p => p.Blog)
    .LoadAsync();

Each call sends one query and fills the navigation on the tracked entity. The beauty of it is that the cost is visible in the code: you can see a query happening, and you can decide not to do it.

Query() gives you an IQueryable over the relationship, so you can filter or aggregate in the database instead of loading everything:

C#
int published = await db.Entry(blog)
    .Collection(b => b.Posts)
    .Query()
    .CountAsync(p => p.Published);          // SELECT COUNT(*) ... WHERE BlogId = @id AND Published

var latest = await db.Entry(blog)
    .Collection(b => b.Posts)
    .Query()
    .OrderByDescending(p => p.CreatedAt)
    .Take(3)
    .ToListAsync();                          // returns the posts, does not fill blog.Posts' load state

blog.Posts.Count would only count what is already in memory, which is why querying through Query() is more honest for large collections.

Check before loading

IsLoaded tells you whether a navigation has been loaded for this entity, so you avoid duplicate queries:

C#
var entry = db.Entry(blog).Collection(b => b.Posts);
if (!entry.IsLoaded)
{
    await entry.LoadAsync();
}

Here is a stand-in with exactly this shape: a tracked wrapper whose Load runs a counted query once:

C# Stand-in: explicit loading with IsLoaded

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Lazy loading

With lazy loading the related data loads automatically the first time you touch the navigation. You write blog.Posts and EF Core silently runs a query. It is the most convenient style and the easiest to misuse.

There are two ways to switch it on.

1. Proxies. Install Microsoft.EntityFrameworkCore.Proxies, call UseLazyLoadingProxies(), and make every navigation virtual:

C#
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseSqlServer(connectionString).UseLazyLoadingProxies());

public class Blog
{
    public int Id { get; set; }
    public virtual List<Post> Posts { get; set; } = new();     // virtual: the proxy overrides it
}

EF Core then returns a dynamically generated subclass of Blog whose Posts getter runs the load. Your classes must be non-sealed with public or protected constructors.

2. Without proxies, with ILazyLoader. Inject the loader into the entity (no virtual, no subclass):

C#
public class Blog
{
    private readonly ILazyLoader _loader;
    private List<Post> _posts = new();

    public Blog(ILazyLoader loader) => _loader = loader;

    public List<Post> Posts
    {
        get => _loader.Load(this, ref _posts);
        set => _posts = value;
    }
}

This ties your entity to an EF Core interface, which many teams dislike in a clean domain model.

The trap: N+1 queries

C#
foreach (var blog in await db.Blogs.ToListAsync())      // 1 query
{
    Console.WriteLine(blog.Posts.Count);                // 1 more query per blog, silently
}

With 500 blogs that is 501 round trips, and nothing in the loop looks expensive. This is the N+1 problem, and it is why many teams ban lazy loading or log a warning when it happens.

sequenceDiagram
    participant C as Your code
    participant E as EF Core
    participant D as Database
    C->>E: ToList() blogs
    E->>D: SELECT * FROM Blogs
    D-->>E: 3 rows
    loop for each blog
        C->>E: blog.Posts
        E->>D: SELECT * FROM Posts WHERE BlogId = @id
        D-->>E: rows
    end

The loop looks cheap but triggers one hidden query per iteration.

Other lazy-loading problems:

  • It fails after the context is gone. Reading blog.Posts after the DbContext was disposed throws (or returns nothing, with ILazyLoader), a classic bug in web APIs that serialize entities.
  • Serialization surprises. A JSON serializer walks every property, so serializing one entity can load the whole database through lazy loading and loop forever through cycles.
  • Synchronous only. Lazy loading runs a blocking query from a property getter; there is no async version.

Here is a stand-in that shows the hidden cost using Lazy<T>:

C# Stand-in: lazy loading and N+1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Four blogs, five queries. Scale the list and you scale the problem.

Which strategy should I use?

Strategy Best when Risk
Eager (Include) You know the shape of data you need Over-fetching, cartesian explosion
Projection (Select) You only read some values Cannot update the result
Explicit (Load) A rare branch needs related data Easy to forget in a loop
Lazy Quick prototypes, desktop apps with a long-lived context N+1, disposed-context bugs

A strong default for web apps: projection or eager loading, never lazy loading, with Load as a rare exception. If you do use proxies, add a logging filter for lazy loads so they are not silent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call loads a collection navigation on an entity you already have?

    Explicit loading goes through Entry, then Collection or Reference, then Load.
  2. 2. What must you do to use lazy-loading proxies?

    The proxy subclasses your entity and overrides virtual navigation properties.
  3. 3. What is the N+1 problem?

    The loop triggers a separate query per parent, which is slow when N is large.
  4. 4. Why is Entry(blog).Collection(...).Query().CountAsync() better than blog.Posts.Count on a large collection?

    Query() builds a SQL COUNT instead of materializing the whole collection.

Summary

  • Explicit loading uses Entry(...).Collection/Reference(...).Load (and Query() for filtered or aggregate queries); IsLoaded prevents duplicates.
  • Lazy loading loads on first access via proxies or ILazyLoader, which is convenient and dangerous.
  • Lazy loading causes N+1 queries, disposed-context errors and serialization surprises.
  • Prefer eager loading and projection; use explicit loading for rare branches.

Next: Inheritance mapping (TPH, TPT, TPC)