Entity Framework Core Mastery

Eager Loading vs Explicit Loading (Include)

1 Views Updated 5/4/2026

Eager Loading vs Explicit Loading (Include)

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.

1. Eager Loading (The Standard Approach)

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);

2. Filtered Includes (.NET 5+)

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);

3. Explicit Loading

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();
}

4. Interview Mastery

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."

Entity Framework Core Mastery
1. Foundations & Architecture
Introduction to Object Relational Mapping (ORM) Entity Framework Core Architecture & Providers Setup and DbContext Integration Code-First vs Database-First Approaches Reverse Engineering Existing Databases (Scaffolding)
2. Code-First Modeling
Entity Conventions & Data Annotations The Fluent API Deep Dive (OnModelCreating) Primary Keys, Composite Keys, & Guids Required Properties & Database Defaults Value Conversions (Enums & Strongly Typed IDs)
3. Relational Architecture
One-to-Many Relationships & Foreign Keys One-to-One Relationships (Dependent Entities) Many-to-Many Relationships & Navigation Properties Owned Entity Types (Value Objects) Table-per-Hierarchy (TPH) Inheritance
4. Data Querying & LINQ
Basic LINQ Queries & IQueryable Execution Tracking vs No-Tracking Queries (Performance) Eager Loading vs Explicit Loading (Include) Lazy Loading Pitfalls & Proxies Client vs Server Evaluation Parsing
5. Manipulating Data (CUD)
Adding, Updating, and Removing Entities The ChangeTracker and Entity States Disconnected Entities in Web APIs Batch Updates and Deletes (.NET 7+)
6. Advanced Performance & Scale
Concurrency Tokens and Optimistic Locking Raw SQL Queries and Views (FromSqlRaw) Compiled Queries for High Throughput Interceptors (Logging & Auditing Data Changes) DbContext Pooling Mechanisms Managing Complex EF Core Migrations (CI/CD)