Why doesn't Include have any effect?

I am doing the following LINQ Query which works but doesn't return the navigation property Person filled, I get null.

public IEnumerable<SharePeople> GetSharePeopeByCarId(int carId)
{
    return from q in _context.Cars
           join s in _context.Shares 
               on q.CarId equals s.Car.CarId
           join p in _context.SharePeople.Include(p => p.Person) 
               on s.ShareId equals p.ShareId
           where q.CarId == carId
           select p;
}

I have no idea why, since when I do the regular extension method like _context.SharePeople.Include(p => p.Person) it works.


This post clearly describes when Include does and doesn't have effect.

The critical part is the shape of the query, i.e. the selected columns. If anything changes the shape after an Include, the Include not longer works.

In your query the shape changes four times, in these statement parts:

  1. from q in _context.Cars: the query would return only Car columns
  2. join s in _context.Shares: Car + Share columns
  3. join p in _context.SharePeople: Car + Share + SharePeople columns. Here's the Include.
  4. select p, only SharePeople columns

Once you're aware of it, the remedy is simple:

(from q ... select p).Include(p => p.Person)

This also applies when the shape of the query seemingly doesn't change, but the query produces a projection. Suppose you'd have select new { q, s, p }. This would still select Car + Share + SharePeople columns, the same as before the Include. However, the query produces an anonymous type. This type itself doesn't have any navigation properties that could be populated by an Include, so again, the Include doesn't do anything. This is by design.