Common EF Core mistake: using explicit includes on select queries

Entity Framework Core has the Include operator that can be used to load related data.


var blogArticles = context.BlogPosts
                            .AsNoTracking()
                            .Include(x => x.Author)
                            .ToList();

In this example the query will return a list of blog posts and informations about the author of each of them. It's convenient, short, understandable and clean but it has two tradeoffs:

With Entity Framework Core, developers are used to some magic happening in the background but they may be think it happens a little more than it does. In this case, developers can think that Entity Framework will analyze the usage of the data they manipulate to optimize the query but it does not so if you ask Entity Framework Core to return some data you don't need, it will do it.

An easy and clean way to fix this is to use implicit includes over explicit ones.


var blogArticles = context.BlogPosts
                            .AsNoTracking()
                            .Include(x => x.Author)
                            .Select(x=> new BlogPostDetails
                              {
                                Id = x.Id,
                                Title = x.Title,
                                Published = x.Published,
                                AuthorFirstName = x.Author.FirstName,
                                AuthorLastName = x.Author.LastName,
                                AuthorProfilePicture = x.Author.ProfilePicture
                              });

By using implicit includes, only the data you use will be returned by Entity Framework Core. So if some day you remove or comment the three line about the author in our example, the inner join that happen in the background will automatically be deleted.

It's a pretty basic EF Core usage but querying more data than needed is a very common mistake that can result to huge useless usage of memory, processing and requests slownesses.

Make application better and faster often starts with details.

Note: if you wonder what is the AsNoTracking() in the query, read the previous post about it: Common EF Core mistake: not using the difference between Tracking and No-Tracking Queries

October 24, 2023
  • Entity Framework Core
  • EF Core
  • Implicit includes
  • Explicit includes