嵌套列表的EF6 Single LINQ查询

时间:2017-01-12 13:45:06

标签: c# entity-framework linq

我想使用单个LINQ查询来使用EntityFramework填充数据库实体中的嵌套列表。

我有3个表实体。 第一课Cities包含List<Houses>Houses包含List<Residents>

那些课程:

class Cities
{
    long CityId {get;set;} 
    string Name {get;set;} 
    List<House> Houses {get;set;} 

}

class Houses 
{
    long CityId {get;set;} 
    string Address {get;set;} 
    List<Resident> Residents {get;set;}

}

class Residents 
{
   long HouseId {get;set;} 
   string FirstName {get;set;} 
   string LastName {get;set;} 
}

我想要实现的是:

var cities = ( from city in db.Cities
               select new  // Creating anonymous type to fill List of Houses 
               {
                  CityId = city.CityId,
                  Name   = city.Name, 
                  Houses = db.Houses.Where(h=>h.CityId == city.CityId)
                                    .Select( new // Another anonymous type, but this time this isn't working
                                    {
                                        HouseId = h.HouseId,
                                        Address = h.Address,
                                        Residents = db.Residents.Where(r=>r.HouseId == h.HouseId).ToList()
                                    }).ToList()
                                    .Select( h => new Houses
                                    {
                                        HouseId = h.HouseId,
                                        Address = h.Address,
                                        Residents = h.Houses
                                    }).ToList()
               })
               .ToList()
               .Select( c=> new Cities
               {
                  CityId = c.CityId
                  Name   = c.Name, 
                  Houses = c.Houses
               }).ToList()

很遗憾,我收到错误The entity or complex type Houses cannot be constructed in a LINQ to Entities

它适用于Houses = db.Houses.Where(h=>h.CityId ==city.CityId).ToList()。 但由此我在Residents中失去了Houses

甚至可以使用一个LINQ查询吗?

2 个答案:

答案 0 :(得分:5)

您只需要将房屋和居民纳入您的城市查询:

var cities = db.Cities.Include(c => c.Houses.Select(h => h.Residents)).ToList();

答案 1 :(得分:0)

您应该使用导航属性,而不是单独的exit访问

Add

没有检查整个语法,只是将db替换为var Cities = (from city in db.Cities select new // Creating anonymous type to fill List of Houses { CityId = city.CityId, Name = city.Name, Houses = city.Houses.Select( new { HouseId = h.HouseId, Address = h.Address, Residents = h.Residents.ToList() }).ToList() .Select( h => new Houses { HouseId = h.HouseId, Address = h.Address, Residents = h.Houses }).ToList() }) .ToList() .Select( c=> new Cities { CityId = c.CityId Name = c.Name, Houses = c.Houses }).ToList() (与db.Houses.Where(...)相同),因此可能还有其他一些问题。