当前位置:  开发笔记 > 编程语言 > 正文

嵌套列表的EF6 Single LINQ查询

如何解决《嵌套列表的EF6SingleLINQ查询》经验,为你挑选了1个好方法。

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

我有3个表实体.第一类Cities包含ListHouses包含List.

那些课程:

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

}

class Houses 
{
    long CityId {get;set;} 
    string Address {get;set;} 
    List 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().但与我失去ResidentsHouses.

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



1> Sergey Berez..:

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

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

推荐阅读
mobiledu2402852357
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有