Why doesn't Include have any effect?

和自甴很熟 提交于 2019-11-26 08:57:25

问题


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.


回答1:


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.




回答2:


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);



来源:https://stackoverflow.com/questions/29300553/why-doesnt-include-have-any-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!