Entity Framework: Inheritance and Include

I’m pretty sure what CatZ suggests doesn’t work.

I don’t think you can do this using Include, but you can achieve the same effect using a projection trick see this How to Sort Relationships in the Entity Framework

What you need to do is something like this:

var results = from d in ctx.Departments
              select new {
                   d, 
                   employees = d.Employees.Select(
                      e => new {
                          e, 
                          location = e is RemoteEmployee ? 
                                     (e as RemoteEmployee).Location : 
                                     null
                     }
                   )
              };


foreach (var result in results)
{
    var re = result.d.Employees.First() as RemoteEmployee;
    Console.WriteLine("{0} {1} works from {2}", 
           re.Firstname, re.Surname, re.Location.Name);
}

Notice that you don’t need to use the anonymous types to get the data, essentially doing the projection has a side-effect of filling the collections on you department because of a feature of the Entity Framework called fixup.

Hope this helps
Alex

Leave a Comment