Reputation: 534
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.
Upvotes: 1
Views: 650
Reputation: 109109
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:
from q in _context.Cars
: the query would return only Car
columnsjoin s in _context.Shares
: Car
+ Share
columnsjoin p in _context.SharePeople
: Car
+ Share
+ SharePeople
columns. Here's the Include.select p
, only SharePeople
columnsOnce 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.
Upvotes: 5
Reputation: 534
Using ste-fu approach it did not worked, but with a variation of it I was able to put it to work.
I guess Gert Arnold answered why it does not work, but since I got it working here is the code:
var sharePeople = Context.SharePeople.Include("Person");
return sharePeople.Where(s => s.Shares.Car.CarId == carId);
Upvotes: 0