Imagine this: you’re building a blog application. A user visits your API to view their blog post and expects to see not just the post but also the comments on that post—and maybe even who made each comment. Now ask yourself this:
Do I want to make one big efficient call to the database, or should I grab each piece one by one?
If your gut says, “One and done,” then you're thinking about eager loading. So let’s dive deep into what it is, how it works, and how you can use it wisely in your ASP.NET Core Web API.
What Is Eager Loading?
Eager loading is a technique used with Entity Framework Core (EF Core) where you load related data alongside your main data in a single query. It's like ordering a combo meal instead of going back to the counter for fries and then again for your drink.
By using .Include() and .ThenInclude(), you’re telling EF Core:
Hey, while you’re grabbing that Blog, go ahead and pull in the Posts and their Comments too.
Why Use Eager Loading?
Here’s the deal
- Performance boost: One query instead of many.
- Avoid the N+1 problem: Imagine fetching 1 blog and 50 posts with separate queries—EF will hit the database 51 times!
- Cleaner API results: Users don’t have to make extra requests to get the full picture.
Real-World Example. Blog, Posts, and Comments
Let’s build a sample project:
public class Blog
{
public int BlogId { get; set; }
public string Title { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
public List<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string Message { get; set; }
public string AuthorName { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
}
This setup gives us:
- A Blog with many Posts
- Each Post with many Comments
DbContext Setup
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
Sample Seed Data
Let’s seed some mock data for testing:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().HasData(new Blog { BlogId = 1, Title = "Tech with Jane" });
modelBuilder.Entity<Post>().HasData(
new Post { PostId = 1, Content = "ASP.NET Core is awesome!", BlogId = 1 },
new Post { PostId = 2, Content = "Entity Framework Tips", BlogId = 1 }
);
modelBuilder.Entity<Comment>().HasData(
new Comment { CommentId = 1, Message = "Loved it!", AuthorName = "John", PostId = 1 },
new Comment { CommentId = 2, Message = "Very helpful!", AuthorName = "Alice", PostId = 1 },
new Comment { CommentId = 3, Message = "Great explanation.", AuthorName = "Sara", PostId = 2 }
);
}

Join the conversation! Your thoughts help the community grow.