Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework recursively include collection for each entity from included collection

Tags:

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?

like image 944
Ian Vink Avatar asked Jul 24 '14 22:07

Ian Vink


2 Answers

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.

like image 167
rmtz Avatar answered Oct 18 '22 01:10

rmtz


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;

like image 34
D Stanley Avatar answered Oct 18 '22 01:10

D Stanley