Sub topic 11
Loading Related Data
In the chapter on relationships, you linked a Blog to its many Post objects. That link lives in a navigation property, which is a property that points to another entity, such as Blog.Posts or Post.Blog. This chapter covers how EF Core fills those properties with data from the database.
A query does not load related data unless you ask for it. If you query blogs, EF Core reads the Blogs table and leaves the Posts table alone. EF Core gives you three ways to load related data:
- Eager loading gets the related data in the same query, using
Include. - Explicit loading gets the related data later, when your code asks for it.
- Lazy loading gets the related data automatically the first time your code reads the navigation property.
This chapter uses the Blog, Post, and BloggingContext classes from earlier chapters.
Why Related Data Is Not Loaded by Default
Picture a blog with 10,000 posts. If EF Core loaded every post each time you read a blog, a simple list of blog URLs would pull huge amounts of data. EF Core avoids that by loading only what you request.
This default causes a common beginner surprise. In our model, Posts starts as an empty list (= new()). If you forget to load the posts, blog.Posts.Count is 0. The blog may still have posts in the database. EF Core just did not read them.
The Three Loading Strategies
Eager Loading with Include
Eager loading means "load this related data now, together with the main data." You ask for it with the Include method.
The program below adds test data and then reads it back with eager loading. Put it in Program.cs, next to the entity and context classes you already wrote, and run it with dotnet run.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
// Add sample data only if the database is empty
if (!await db.Blogs.AnyAsync())
{
var blog = new Blog { Url = "https://example.com/ef" };
blog.Posts.Add(new Post { Title = "Intro to EF Core", Content = "..." });
blog.Posts.Add(new Post { Title = "Migrations", Content = "..." });
db.Blogs.Add(blog);
await db.SaveChangesAsync();
}
// Eager loading: blogs and their posts in one go
var blogs = await db.Blogs
.Include(b => b.Posts)
.ToListAsync();
foreach (var b in blogs)
{
Console.WriteLine($"{b.Url} has {b.Posts.Count} posts");
foreach (var p in b.Posts)
{
Console.WriteLine($" - {p.Title}");
}
}Include(b => b.Posts) tells EF Core to fill each blog's Posts list. Remove the Include line and run the program again. The output will say has 0 posts, which shows the surprise from the warning above.
Include also works on the other side of a relationship. db.Posts.Include(p => p.Blog) loads each post together with its blog.
Going deeper with ThenInclude
Say a Post had its own Comments collection. Then you could load blogs, their posts, and the posts' comments like this: db.Blogs.Include(b => b.Posts).ThenInclude(p => p.Comments). ThenInclude continues from the last thing you included. Our model has no comments, so this is only a pattern to remember.
Filtered Include
Sometimes you want only some of the related rows. You can put a filter inside Include:
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blogsWithEfPosts = await db.Blogs
.Include(b => b.Posts.Where(p => p.Title.Contains("EF")))
.ToListAsync();
foreach (var b in blogsWithEfPosts)
{
Console.WriteLine($"{b.Url}: {b.Posts.Count} matching posts");
}The filter limits which posts are loaded into each blog. It does not remove any blogs. A blog with no matching posts still appears, with an empty Posts list.
Explicit Loading
Explicit loading means you load the main entity first and then load related data later, only if you need it. You start with db.Entry(entity), which gives you EF Core's tracking information for that entity.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blog = await db.Blogs.FirstAsync();
Console.WriteLine($"Before: {blog.Posts.Count} posts");
// Load a collection navigation
await db.Entry(blog).Collection(b => b.Posts).LoadAsync();
Console.WriteLine($"After: {blog.Posts.Count} posts");
// Load a reference navigation (a single related entity)
var post = await db.Posts.FirstAsync();
await db.Entry(post).Reference(p => p.Blog).LoadAsync();
Console.WriteLine($"Post '{post.Title}' belongs to {post.Blog.Url}");
// Count related rows without loading them
int count = await db.Entry(blog)
.Collection(b => b.Posts)
.Query()
.CountAsync();
Console.WriteLine($"Count from database: {count}");Collection(...)is for navigations that hold many items, such asPosts.Reference(...)is for navigations that hold one item, such asBlog.Query()returns a LINQ query over the related rows, so you can filter or count them without loading them all.
Explicit loading needs a tracked entity, which means one the context is watching. It does not work on results from AsNoTracking queries.
Lazy Loading
Lazy loading means EF Core loads a navigation property the first time your code reads it, without any Include or LoadAsync call. It is turned off by default. To turn it on:
- Add the package:
dotnet add package Microsoft.EntityFrameworkCore.Proxies. - Call
UseLazyLoadingProxies()when configuring the context. - Mark the navigation properties
virtual, so EF Core can create a proxy class that overrides them.
using Microsoft.EntityFrameworkCore;
public class LazyBlog
{
public int LazyBlogId { get; set; }
public string Url { get; set; } = "";
public virtual ICollection<LazyPost> Posts { get; set; } = new List<LazyPost>();
}
public class LazyPost
{
public int LazyPostId { get; set; }
public string Title { get; set; } = "";
public int LazyBlogId { get; set; }
public virtual LazyBlog Blog { get; set; } = null!;
}
public class LazyContext : DbContext
{
public DbSet<LazyBlog> Blogs => Set<LazyBlog>();
public DbSet<LazyPost> Posts => Set<LazyPost>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options
.UseLazyLoadingProxies()
.UseSqlite("Data Source=lazy.db");
}With this setup, reading blog.Posts runs a query in the background if the posts are not loaded yet. Lazy loading is convenient, but it hides database work. If you loop over 100 blogs and read Posts on each one, EF Core runs 1 query for the blogs and then 100 more for the posts. This is the N+1 problem, which the performance chapter covers in more detail.
Comparing the Strategies
| Strategy | How you ask | When the query runs | Main risk |
|---|---|---|---|
| Eager | `Include`, `ThenInclude` | With the main query | Loading more data than you need |
| Explicit | `Entry(...).Collection/Reference(...).LoadAsync()` | When you call `LoadAsync` | Forgetting to call it |
| Lazy | Proxies plus `virtual` navigations | On first access of the navigation | Hidden N+1 queries |
A Related Behavior: Fix-Up
EF Core sometimes fills navigations without any of these methods. If the context is already tracking some posts and you then load their blog, EF Core links them together automatically. This is called relationship fix-up. It explains why a navigation can contain data even when you never used Include.
When You Need Only a Few Fields
If you only need a couple of values, such as a post title and its blog URL, you do not have to load whole entities. A Select projection, which you saw in the LINQ chapter, can reach across navigations, and EF Core writes the join for you: db.Posts.Select(p => new { p.Title, p.Blog.Url }). For read-only screens, this is often the cheapest option.
Exercise
You run var blog = await db.Blogs.FirstAsync(); and blog.Posts.Count prints 0, but the database has 5 posts for that blog. Name two ways to fix this without turning on lazy loading.
Show answer
Use eager loading by adding .Include(b => b.Posts) before FirstAsync(), or use explicit loading after the query with await db.Entry(blog).Collection(b => b.Posts).LoadAsync();. Either way, Posts is filled and the count is 5.
Exercise
A page shows 50 blogs and the number of posts in each one. Lazy loading is on, and the code reads blog.Posts.Count inside a loop. About how many queries run, and what is a better approach?
Show answer
About 51 queries run: 1 for the blogs and 1 per blog for its posts (the N+1 problem). A better approach is a projection like db.Blogs.Select(b => new { b.Url, PostCount = b.Posts.Count() }), which gets the counts in a single query without loading any posts.