Why Entity Framework Include Method Doesn’t Always Work

I recently had a problem with the following code not working as expected:

var services = context.Benefits
    .Include(b => b.Services.Select(s => s.ServiceCategory))
    .SelectMany(b => b.Services)
    .ToList();

I’m using a Select within the Include to load the ServiceCategory object associated with each Service in the Services navigation property of the Benefit object. I’ve used Include a lot in the past and never had a problem until now.

As it turns out, Include does not work if you change the shape of the query after specifying the Include method. In my case, SelectMany caused the shape to change from Benefit to Service.

Fortunately, the solution is simple. Specify the Include after changing the shape as follows:

var services = context.Benefits
    .SelectMany(b => b.Services)
    .Include(x => x.ServiceCategory)
    .ToList();

I found the solution, and an explanation for this behavior, in an MSDN blog post.

3 thoughts on “Why Entity Framework Include Method Doesn’t Always Work”

  1. Thank you so much! This killed me for several hours. Problem was, I have a generic repository that handles the Include() logic for me, and then returns the IQueryable. I then chained on the .SelectMany() call to the result of the repository method, effectively negating all of the work it had done to apply the Include methods.

    Here's the repository code:

    public IQueryable Find(
    Expression> predicate,
    params Expression>[] entitiesToInclude)
    {
    return entitiesToInclude.Aggregate(
    DbSet.Where(predicate),
    (current, entityToInclude) => current.Include(entityToInclude));
    }

    The solution was to create a custom repository that inherited from the generic repository, and I added a custom method to handle the special case, e.g. GetListOfFooChildren()

Leave a Reply

Your email address will not be published. Required fields are marked *