LESSON 8 OF 19

Incorrect Include and ThenInclude Usage: Missing, Excessive or Repeated Related Data

Learn how to diagnose Include and ThenInclude problems in Blog, Post and Author relationships using projection, filtered include, AsSplitQuery and AsSingleQuery.

35 dk 95

Introduction

Loading related data in Entity Framework Core often appears to be as simple as adding a few Include and ThenInclude calls. However, including too many navigation properties, placing ThenInclude at the wrong point in a chain, or repeatedly including the same collection with different filters can produce surprising results and serious performance problems.

In this lesson, we will use Blog, Post and Author entities. The goal is not merely to load related data, but to determine what is actually required, inspect the SQL generated by EF Core and make an informed choice between a single query and split queries.

In EF Core, eager loading retrieves related data as part of the main query. Include selects a navigation property, while ThenInclude continues from a navigation that was included previously. Nevertheless, going deeper in every relationship is not automatically correct. The purpose of the query, the size of the result and the SQL generated by the database must all be considered together.

Sample model and DbContext

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public ICollection<Post> Posts { get; set; } = new List<Post>();
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public bool IsPublished { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; } = null!;
    public int AuthorId { get; set; }
    public Author Author { get; set; } = null!;
}

public class Author
{
    public int Id { get; set; }
    public string DisplayName { get; set; } = string.Empty;
    public ICollection<Post> Posts { get; set; } = new List<Post>();
}

In this model, one blog has many posts, and each post belongs to one author. Therefore, the navigation path from a blog to a post and then to its author is Blog -> Posts -> Author.

Building a correct ThenInclude chain

To load blogs, their posts and the author of each post, use the following query:

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .ToListAsync();

The Include call selects Blog.Posts. The following ThenInclude continues from the Post entity and selects Post.Author. Each step in the chain must continue from the entity type returned by the previous navigation.

The following example is invalid for this purpose:

var blogs = await db.Blogs
    .ThenInclude(blog => blog.Posts)
    .ToListAsync();

ThenInclude cannot be used by itself; it must follow an Include. Similarly, attempting to access a navigation that does not belong to the current entity type indicates a mismatch between the query and the model. When working with deep relationships, verify the type returned at each step of the chain.

The missing navigation problem

A common mistake is loading posts while forgetting to load their authors:

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ToListAsync();

This query loads Blog.Posts, but it does not explicitly load post.Author. If lazy loading is not enabled, the author may not be available when the application accesses it. The corrected query is:

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .ToListAsync();

If a post has both an author and another collection navigation, such as tags, separate include branches are required. Do not try to combine unrelated branches into one ThenInclude chain.

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Tags)
    .ToListAsync();

In this example, the second Include starts again at Blog.Posts so that the query can continue through a different branch. However, as the number of branches grows, the generated join structure may become very large. At that point, projection or a split query may be a better design.

Unnecessary Include calls and oversized result sets

If an endpoint returns only the blog name, published post titles and author names, loading the complete entity graph is unnecessary. The following query works, but it can transfer large fields such as Content and many unused columns:

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .ToListAsync();

Projection provides a more precise alternative:

var result = await db.Blogs
    .Select(blog => new
    {
        blog.Id,
        blog.Name,
        Posts = blog.Posts
            .Where(post => post.IsPublished)
            .OrderByDescending(post => post.Id)
            .Select(post => new
            {
                post.Id,
                post.Title,
                AuthorName = post.Author.DisplayName
            })
            .ToList()
    })
    .ToListAsync();

Projection selects only the columns that the application needs. It also creates a result shaped like an API or view model, which reduces the risk of accidentally exposing or modifying a large entity graph. For read-only scenarios, this is often clearer and more efficient than a long list of Include calls.

Controlled eager loading with filtered Include

Sometimes the entity graph is needed, but loading every post is not. For example, you may want only the five most recent published posts for each blog:

var blogs = await db.Blogs
    .Include(blog => blog.Posts
        .Where(post => post.IsPublished)
        .OrderByDescending(post => post.Id)
        .Take(5))
    .ThenInclude(post => post.Author)
    .AsNoTracking()
    .ToListAsync();

Filtered include allows operations such as Where, ordering and Take to be applied to a collection navigation. This prevents unnecessarily large post collections from being transferred.

There is an important detail with tracking queries. If related entities were loaded earlier in the same DbContext, navigation fix-up can cause them to appear in the filtered include result. For example, if all posts were loaded first and a later query asks for only published posts, other tracked posts may still appear in the navigation collection. For reporting and API queries, consider a short-lived context, AsNoTracking or projection.

Be careful when applying multiple filters to the same collection navigation. If different filtered branches are required, projection is often easier to understand. Repeating identical filters across include branches is possible, but it may make the query more complex than necessary.

Choosing between AsSingleQuery and AsSplitQuery

EF Core can load related collections through joins in a single SQL query. This is suitable for small and limited relationships. However, when several collection navigations are included together, duplicated rows can produce a cartesian explosion.

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .Include(blog => blog.Categories)
    .AsSingleQuery()
    .ToListAsync();

If each blog has many posts and categories, the join result may repeat blog data across many rows. In that situation, AsSplitQuery can reduce the size of the joined result:

var blogs = await db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .Include(blog => blog.Categories)
    .AsSplitQuery()
    .ToListAsync();

A split query executes the main blog query and collection-navigation queries separately. This can avoid large join results, but it also means additional database round-trips. Because the queries are executed separately, changes made between them can affect consistency. For critical operations, evaluate transaction isolation and the consistency requirements of the application.

AsSingleQuery is not always wrong. It can be the better option when the relationship set is small, the result is limited and minimizing round-trips is important. Choose based on actual data volume, SQL plans, network traffic and measurements rather than relying only on defaults.

Inspecting generated SQL

One of the best ways to understand query behavior is to inspect the SQL generated by EF Core. Use ToQueryString to view the query before executing it:

var query = db.Blogs
    .Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .AsSplitQuery();

Console.WriteLine(query.ToQueryString());

Application-level SQL logging can also reveal the number of commands, parameters and execution times. If you see more queries than expected, check for lazy loading, navigation access inside loops or incorrectly designed explicit loading.

Common mistakes

  • Including everything: This transfers unnecessary columns and rows. Define the purpose of the query first.
  • Building the ThenInclude chain incorrectly: Confirm that each ThenInclude continues from the type returned by the preceding navigation.
  • Reusing a tracking context with filtered Include: Navigation fix-up may expose entities outside the filter.
  • Loading multiple collections in one query: This can produce cartesian explosion and high memory usage.
  • Using AsSplitQuery without measuring: It can reduce join duplication while increasing the number of round-trips.
  • Returning an entity graph instead of a projection: APIs may transfer unnecessary and oversized data.

Short practice exercise

  1. Create a database containing blogs, posts and authors. Add at least ten posts to each blog and assign an author to every post.
  2. Run a query using Include(blog => blog.Posts) and observe that only posts are explicitly loaded.
  3. Add ThenInclude(post => post.Author) and compare the result.
  4. Replace the query that loads every post with a filtered include that returns only the latest three published posts.
  5. Run the query with both AsSingleQuery and AsSplitQuery, then inspect the output of ToQueryString.
  6. Finally, write a projection that returns only the blog name, post title and author name.

Conclusion

Include and ThenInclude are powerful tools for loading related data explicitly and predictably, but adding every available navigation is rarely the right solution. Build the chain correctly when a navigation is missing, use projection when unnecessary data would otherwise be loaded and consider filtered include for large collections.

When multiple collection navigations are included, compare AsSingleQuery and AsSplitQuery using generated SQL and real performance measurements. Tracking behavior, navigation fix-up, row duplication and round-trip count must be evaluated together. This approach leads to relationship queries that are not only correct, but also predictable and efficient in production.

Sources