Abdurahman Almatrodi
Abdurahman Almatrodi

Reputation: 65

Retrieve Related Data (Multi-Level)

I have three classes:

  1. Country.
  2. District.
  3. Province

    public class Country
    {
        public Country()
        {
            Districts = new HashSet<District>();
        }
    
        public string Name { get; set; }
        public virtual ICollection<District> Districts { get; private set; }
    }
    
    public class Ditrict
    {
        public Ditrict()
        {
            Provinces = new HashSet<Province>();
        }
    
        public string Name { get; set; }
        public virtual ICollection<Province> Provinces { get; private set; }
    }
    
    public class Province
    {
        public string Name { get; set; }
    }
    

What I need to accomplish is how to include all Provinces, Districts (Even if there is no Provinces), Country (Even if there is no Districts) in one command using Ling.

The reason is that I am going to use DevExpress Grid, so the user can see the Country and add a new District, and can see the District and add a new Province.

My all attempts failed, because what I get is the Country that have Disctrict and District that have Province.

Btw, I am using:

[Solution]

After many attempts and searching, I discovered that I need to use .ThenInclude to the third level Provinces. Like:

Countries = dbContext
                .Countries
                .Include(c => c.Districts)
                .ThenInclude(p => p.Provinces)
                .ToList();

Upvotes: 0

Views: 66

Answers (1)

Sina Iravanian
Sina Iravanian

Reputation: 16286

It would have been nice if you could send us what you have tried. Roughly speaking you can use Include to eager load dependent entities and collections. If you query the chain of entities starting from Country it will retrieve all the countries even if they don't have Districts:

using (var dbContext = new YourDbContext())
{
    return dbContext.Countries
        .Include(c => c.Districts.Select(d => d.Provinces))
        .ToList();
}

I guess the reason you retrieve countries only if they have districts, etc, is because your query starts from the other end of the chain (Province) rather than starting from Country as above.

Upvotes: 1

Related Questions