LINQ .Include() properties from sub-types in TPH inheritance LINQ .Include() properties from sub-types in TPH inheritance json json

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:

  1. OfType<Department>(): You can't Union both lists directly. You have to cast one of them to IEnumerable<Department> to be able to Union the other. But...

  2. .AsEnumerable(): If you only do the cast, EF will conclude it's dealing with Depeartments, and it won't accept the Include of the Manager. By including AsEnumerble 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 Departments 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.