[英]EF6 Single LINQ Query for nested Lists
我只想使用EntityFramework使用單個LINQ查詢來填充數據庫實體中的嵌套列表。
我有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()
。 但是,這使我失去了Houses
Residents
。
甚至可以用一個LINQ查詢嗎?
您只需要在城市查詢中包括房屋和居民:
var cities = db.Cities.Include(c => c.Houses.Select(h => h.Residents)).ToList();
您應該使用導航屬性,而不是單獨的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(...)
由city.Houses
(有相同的Residents
),所以可能有一些其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.