LINQ包含在一对多的.Where()无法正常工作?

我正在尝试查询用户,包括每个用户的兴趣,但仅限于兴趣符合特定条件的情况:

return db.Users.Include(u => u.Interests.Where(s => s.TenantId == tenantId)) 

但是我收到一个错误:

Include路径表达式必须引用在类型上定义的导航属性。 使用虚线路径作为参考导航属性,使用Select运算符作为集合导航属性。

我玩的想法是把外面的东西推到外面,但却无法让它发挥作用。

要仅包含一些兴趣,您将无法使用Include方法,因为它不支持此function。 您需要手动加入与UsersInterests

 var query = from user in db.Users join interest in db.Interests.Where(s => s.TenantId == tenantId) on user.InterestId equals interest.Id //todo: will need to be updated into interests; select new { user, interests}; 

试试这个:

 return db.Users.Include("Interests").Where(u => u.Interests.Any(i => i.TenantId == tenantId)); 

这会导致加载用户,但仅限于tenantId匹配的位置。 在执行查询时,将为这些用户急切加载与兴趣相关的实体。