0

I am new to the C# Entity Framework. I created three classes - Country - Area - Subarea

There is a many-to-many relationship between Country and Area. There is another many-to-many relationship between Area and Subarea.

A Country can contain many Areas, but there also Areas that belong to more than one country). The same for Area and Subarea.

I created the respective classes and the database tables have been automatically created. The tables for CountryAreas and SubAreaAreas have been created too, so all looks good. Also the foreign keys look fine.

I am able to write data to the tables via (see below).

I am now struggling getting all the Countries with the respective Areas and Subareas selected from the database.

I read a couple of post and it looks like I am lacking basic knowledge about LINQ queries and the Entity Framework.

public class Country
{
    #region attributes
    [Key]
    public string Name { get; set; }
    public List<Area> Areas { get; set; } // virtual enabled lazy loading
    #endregion
}

public class Area
{
    #region attributes
    [Key]
    public string Name { get; set; }
    public virtual List<SubArea> Subareas { get; set; }
    public virtual List<Country> Countries { get; set; }
    #endregion
}

public class SubArea
{
    #region attributes
    [Key]
    public string Name { get; set; }
    public virtual List<Area> Areas { get; set; }
    #endregion
}

public class LocationScoutContext : DbContext
{
    public LocationScoutContext()
        : base("name=LocationScout")
    {
    }

    public DbSet<Country> Countries { get; set; }
    public DbSet<Area> Areas { get; set; }
    public DbSet<SubArea> SubAreas { get; set; }

}


// *** reading the data works fine ***
using (var db = new LocationScoutContext())
{
   db.Countries.Add(newCountry);
   db.SaveChanges();
}


// *** I tried this ***
var allCountries = new List<Countries>();
using (var db = new LocationScoutContext())
{
   var query = from c in db.Countries select c;
}

foreach (var c in query)
{
   allCountries.Add(c);
}

I tried something like shown above but this obviously does not do any join and just gives me the names of the Countries with empty Areas and SubAreas.

Any help is appreciated :-)

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76

1 Answers1

4

Try as follows. This will give all the countries with its areas and subareas.

For EF 6.x:

using (var db = new LocationScoutContext())
{
   var countries = db.Countries.Include(c => c.Areas.Select(a => a.SubAreas)).ToList();
}

For EF Core:

using (var db = new LocationScoutContext())
{
   var countries = db.Countries.Include(c => c.Areas).ThenInclude(a => a.SubAreas).ToList();
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114