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.