When you download a Blog from the database, EF Core does not automatically download its 1,000 associated Posts. The blog.Posts collection will simply be empty (null). You must explicitly instruct EF Core to retrieve related relational data. This is called Loading Strategy.
Eager loading means you specify exactly which relational tables you want to join at the exact moment you write the initial query. You use the .Include() method.
// Fetches the Blog AND executes a SQL LEFT JOIN to fetch all related Posts simultaneously
var blog = await _context.Blogs
.Include(b => b.Posts)
.FirstOrDefaultAsync(b => b.Id == 1);
// Deep Embedding: The ThenInclude() method
// Fetches the Blog -> its Posts -> the Comments on those posts!
var deepBlog = await _context.Blogs
.Include(b => b.Posts)
.ThenInclude(post => post.Comments)
.FirstOrDefaultAsync(b => b.Id == 1);
What if the Blog has 10,000 posts, but we only want to Eager Load the posts that were published this year? Before .NET 5, this was famously difficult. Now, we use Filtered Includes.
var activeBlog = await _context.Blogs
.Include(b => b.Posts.Where(p => p.Year == 2024)) // Filters the JOIN!
.FirstOrDefaultAsync(b => b.Id == 1);
Explicit Loading happens after the main entity has already been downloaded. Imagine you load a Customer object. Based on some C# if statement logic, you suddenly realize you need their Order History. You don't want to re-query the entire Customer; you just want to reach out to the database and grab the missing Orders.
// 1. Download just the Customer (No Includes)
var customer = await _context.Customers.FindAsync(5);
if (customer.IsPremiumAccount)
{
// 2. Explicitly reach back into the database to load the missing collection onto the object!
await _context.Entry(customer)
.Collection(c => c.Orders)
.LoadAsync();
}
Q: "When applying multiple '.Include()' statements (e.g., querying 10,000 Blogs, including Posts, including Authors, including Comments), performance degrades catastrophically with Memory 'OutOfMemoryExceptions'. Why, and how do we fix Cartesion Explosions?"
Architect Answer: "This is the classic Cartesian Explosion problem. When you chain multiple `Includes()` on collection properties, EF Core translates this into a single massive SQL query with multiple `JOIN` statements. If a Blog has 10 Posts and 10 Comments, SQL returns a flat grid multiplying the rows (1x10x10 = 100 rows per Blog), duplicating the underlying Blog data 100 times over the network! EF Core then spends massive CPU cycles deduplicating that data in C# memory. To fix this, we append the `.AsSplitQuery()` method to our LINQ chain. This commands EF Core to NOT use a single massive JOIN. Instead, it fires 3 separate, highly-efficient SQL queries (Select Blogs, Select Posts, Select Comments) and stitches them together safely in memory, bypassing the Cartesian math entirely."