Search code examples
c#entity-frameworkentity-framework-6table-per-hierarchytph

Entity Framework 6 Table Per Hierarchy specific includes


I have a problem with EF6 when I do a Table per Hierarchy mapping. I have an Person class that has Employee and Manager children. The two classes are nearly the same, except for one field: DepartmentId (and the subsequent linked component Department).

class Person {
  public string Name {get; set;}
}
class Employee : Person {}
class Manager : Person {
  public int DepartmentId {get; set;}
  public Department Department {get; set;}
}

I have set up EF with the necessary setup for this kind of thing:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  modelBuilder.Entity<Person>()
     .Map<Employee>(x => x.Requires("Discriminator").HasValue("emp"))
     .Map<Manager>(x => x.Requires("Discriminator").HasValue("man"));

Now my problem is that when I want to include the Department, I can't figure out how to do it. Can anybody help me? Or point me in the right direction with an article or something?


Solution

  • I'm assuming your dbContext only exposes the Person DbSet. Also, you don't indicate if you're trying to get all Person objects or just the Managers. If it's the latter you can use the OfType<T> method to cast to the correct type.

    dbContext.Person
        .OfType<Manager>()
        .Include(m => m.Department)