LINQ Include on a one-to-many with .Where() not working?

前端 未结 2 1143
北恋
北恋 2020-12-21 10:09

I\'m trying to query Users including each user\'s Interests, but only where an Interest meets certain criteria:

  return db.Users.Include(u => u.Interest         


        
相关标签:
2条回答
  • Try this:

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

    This causes the users to be loaded, but only where the tenantId matches. The Interests related entities will be eager loaded for those users when the query executes.

    0 讨论(0)
  • 2020-12-21 10:52

    To include only some of the interests you won't be able to use the Include method, as it doesn't support this. You'll need to manually join the Interests with the Users:

    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};
    
    0 讨论(0)
提交回复
热议问题