In this lesson, you will learn how to use Include to fetch related data in a single database round-trip, effectively solving the performance-draining "N+1 problem."
The N+1 Problem
When you fetch a collection of entities from a database—for example, a list of Blogs—Entity Framework Core by default only retrieves the properties of the Blog entity itself. If you later try to access the Posts collection for each blog in a loop, EF Core will fire an additional query to the database for every single blog iteration. If you have 50 blogs, you end up with 1 initial query plus 50 extra queries. This is the N+1 problem, and it is a major performance bottleneck.
Solving it with Eager Loading
Eager loading tells Entity Framework Core to fetch the related entities at the same time as the main entity. We achieve this by using the Include method, which is available in the Microsoft.EntityFrameworkCore namespace.
When you use Include, EF Core generates a SQL JOIN statement under the hood. This brings both the parent and the related child records into memory in a single efficient query.
// Fetching blogs and their related posts in one trip
var blogs = context.Blogs
.Include(b => b.Posts)
.ToList();
Loading Multiple Levels
You aren’t limited to just one level of relationship. If your Post entity has its own related Comments, you can "chain" your includes using ThenInclude. This allows you to pull down an entire graph of data in one go:
var data = context.Blogs
.Include(b => b.Posts)
.ThenInclude(p => p.Comments)
.ToList();
By specifying exactly what you need upfront, you prevent the application from making unnecessary, repeated trips to the database, ensuring your data access layer remains fast even as your data model grows in complexity. Remember, while eager loading is powerful, it can pull large amounts of data into memory; always consider if a simple projection (using .Select()) might be better if you only need a few specific fields.
Key Takeaway: Use the Include method to fetch related entities in a single query, eliminating N+1 performance issues by loading the entire required object graph at once.