LINQ .Include() properties from sub-types in TPH inheritance
At this way you can find the finance and sports departments and include their properties:
var financeDeparments = context.Departments.OfType<Finance>().Include(p => p.Manager).ToList();var sportDepartments = context.Departments.OfType<Sports>().Include(p => p.Coach).ToList();
A way to get all departments in one list that can be serialized into JSON is
var deparments = context.Departments.OfType<Finance>().Include(p => p.Manager) .AsEnumerable() .OfType<Department>() .Union( context.Departments.OfType<Sports>().Include(p => p.Coach) ).ToList();
Explanation:
OfType<Department>()
: You can'tUnion
both lists directly. You have to cast one of them toIEnumerable<Department>
to be able toUnion
the other. But....AsEnumerable()
: If you only do the cast, EF will conclude it's dealing withDepeartment
s, and it won't accept theInclude
of theManager
. By includingAsEnumerble
you do the subsequent cast in memory and EF never knows about it.
I think this is quite a bunch of contrived code only for sake of serializing.
A totally different option is to make sure the serializing occurs while the context is alive, so lazy loading is triggered to populate the navigation properties. In that case, you could simply serialize Department
s and you'll find all properties of derived types in the JSON. Maybe (if the actual model is more complex than what you show) you have to prevent circular references.
If the number of Department
is not too large I think this is a viable option, even though it will generate a number of queries for lazy loading.