为什么不包含有什么影响?

我正在做以下LINQ查询,但它不会返回导航属性Person填充,我得到null

 public IEnumerable 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; } 

我不知道为什么,因为当我使用像_context.SharePeople.Include(p => p.Person)这样的常规扩展方法时,它可以工作。

这篇文章清楚地描述了Include何时起作用和不起作用。

关键部分是查询的形状 ,即选定的列。 如果在Include后任何内容改变了形状,则Include不再有效。

在您的查询中,形状在这些语句部分中更改了四次:

  1. from q in _context.Cars :查询将只返回Car
  2. join s in _context.SharesCar + Share
  3. join p in _context.SharePeopleCar + Share + SharePeople列。 这是包含
  4. select p ,只select p SharePeople

一旦你意识到它,补救措施很简单:

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

当查询的形状看起来没有改变,但查询产生投影时,这也适用。 假设您select new { q, s, p } 。 这仍然会选择Car + Share + SharePeople列,与Include之前相同。 但是,查询会生成匿名类型。 此类型本身没有可以由Include填充的任何导航属性,因此Include不会执行任何操作。 这是设计的 。

使用ste-fu方法它没有用,但有了它的变化我能够把它用于工作。

我想Gert Arnold回答为什么它不起作用,但是因为我在这里工作的是代码:

var sharePeople = Context.SharePeople.Include("Person");

return sharePeople.Where(s => s.Shares.Car.CarId == carId);