Reputation: 856
I want to use just single LINQ query to fill nested lists in DB Entities using EntityFramework.
I've got 3 Table Entities.
First class Cities
contains List<Houses>
and Houses
contains List<Residents>
.
Those classes:
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;}
}
What I want to achieve is something like that:
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()
Unfortunately I am getting error The entity or complex type Houses cannot be constructed in a LINQ to Entities
.
It works, just for Houses = db.Houses.Where(h=>h.CityId ==city.CityId).ToList()
.
But with that I am loosing Residents
in Houses
.
Is it even possible to do with one LINQ query?
Upvotes: 2
Views: 915
Reputation: 236268
You just need to include houses and residents into your cities query:
var cities = db.Cities.Include(c => c.Houses.Select(h => h.Residents)).ToList();
Upvotes: 5
Reputation: 13458
You should use the navigation properties, not a separate db
access
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()
Didn't check whole syntax, only replaced db.Houses.Where(...)
by city.Houses
(same with Residents
), so there might be some other issues.
Upvotes: 0