I am using table inheritance per hierarchy (TPH) in the Entity Framework. Now I'm looking to get a list - in this example - of departments, where departments can be a subtype. I would like the elements in the collection to include their own custom properties , not just the properties of the base model.
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;} }
I even tried to return an IEnumerable<object> and add a polymorphic method for each subtype that looks like this:
public class Sports : Department { public Coach Coach {get; set;} public object Export() { return new { this.Id, this.DepartmentType, this.Coach } } }
and then follow these steps:
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" } } ]
json inheritance c # linq
NaNerd
source share