I am using table-per-hierarchy (TPH) inheritance in Entity Framework. Now I am looking to get a list of - in this example - Departments where departments can be a sub-type. I'd like the items in the collection to include their own custom properties and not only the Base Model's properties.
How can I achieve this?
public class Department
{
public Department()
{
DepartmentType = this.GetType.Name;
}
public int Id {get; set;}
public string DepartmentType {get; set;}
}
public class Finance : Department
{
public virtual Manager Manager {get; set;}
}
public class Sports : Department
{
public virtual Coach Coach {get; set;}
}
// This obviously crashes instantly
// How can I include Manager if type is Finance and Coach if type is Sports?
context.Departments
.Include(c => (c is Finance) ? c.Manager : null)
.Include(c => (c is Sports) ? c.Coach : null);
I have even tried to return IEnumerable<object>
and add a polymorphic method to each sub-type that looked like this:
public class Sports : Department
{
public Coach Coach {get; set;}
public object Export()
{
return new
{
this.Id,
this.DepartmentType,
this.Coach
}
}
}
and then do something like this:
context.Departments.Select(c => c.Export())
But that doesn't work either.
Desired JSON Usage
[
{ Id: 1, DepartmentType: "Finance", Manager: { Name: "John" } },
{ Id: 2, DepartmentType: "Finance", Manager: { Name: "Harold" } },
{ Id: 3, DepartmentType: "Sport", Coach: { Name: "Fred", SportType: "Soccer" } },
{ Id: 4, DepartmentType: "Finance", Manager: { Name: "Hank" } },
{ Id: 5, DepartmentType: "Sport", Coach: { Name: "Mark", SportType: "Football" } }
]