Entity Framework recursively include collection for each entity from included collection

c# entity-framework linq

Question

I have the following where I am trying to include the addresses of the people in the cities of the countries.

Country country = _db.Countries
               .Include(p=>p.Cities.People.????)
               .Where(....)

Not sure how to work it?

1
23
11/12/2015 2:33:02 PM

Accepted Answer

From the documentation:

To include a collection, a collection, and a reference two levels down:

    query.Include(e => e.Level1Collection.Select(l1 => l1.Level2Collection.Select(l2 => l2.Level3Reference))).

So in your case try

Country country = _db.Countries
               .Include(c=>c.Cities.Select(
                   cc => cc.People.Select(
                   p => p.Addresses)))
               .Where(....)

Access to this extension method requires the directive using System.Data.Entity;

30
6/14/2016 3:28:12 PM

Popular Answer

You have to add an .Include call for each level in you object hierarchy tree:

 var result = db.Countries
            .Include(m => m.Cities)
            .Include(m => m.Cities.Select(v => v.People))
            .Where(....)

Edit : D.Stanley answer is better in terms of compact code, and works as well, I tend to prefer this syntax in terms of modularity.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow