代码之家  ›  专栏  ›  技术社区  ›  Evonet

使用Distinct进行多对多选择查询

  •  0
  • Evonet  · 技术社区  · 12 年前

    我有以下型号:

    public class Person
    {
        public string fullName { get; set; }
        public virtual ICollection<Hobby> hobbies { get; set; }
        public virtual Location location { get; set; }
    }
    
    public class Hobby
    {
        public string hobbyName { get; set; }
        public virtual ICollection<Person> people { get; set; }           
    }
    
    public class Location
    {
       public string locationName { get; set; }
       public virtual ICollection<Person> People { get; set; }
    }
    

    一个人可以有很多爱好,反之亦然,一个人可以只有一个地点。

    我想做一个查询,对于一个给定的地点,返回该地点的所有不同爱好

    因此,如果地点是“达拉斯”,请找到达拉斯的所有人,归还他们的所有爱好,并删除重复项。

    2 回复  |  直到 12 年前
        1
  •  2
  •   har07    12 年前

    您可以尝试以下方式:

    var hobbies = (from h in hobbies
                    where h.people.Any(p => p.location.locationName == "Dallas")
                    select h);
    
        2
  •  0
  •   Ed Freitas    12 年前

    使用FK可以很好地表示关系,因此可以像这样简化查询:

    from p in persons 
    Where p.location.locationName = "London"
    select new 
    {
        person = p,
        hobbies = p.hobbies
    }