Inheritance with.Include in Entity Framework?



I think that there's a similar post on here about this but not exactly the same...

I have two entities in my EF model - let's call them Person and Developer, with the latter inheriting from the former.

I also have an association on Developer called Qualifications. This is not visible on the Person entity.

If I'm writing a query against the context, how do I automatically .Include () the Qualifications of the Developer e.g.

from employee in context.Employee .Include ("Qualifications") select employee

doesn't work... EF complains that the relationship does not exist (I assume because it does not exist on Employee - but there's no Developer entity on the context, just Employee).

9/22/2009 5:32:01 PM

Popular Answer

I've come across this problem and experimented a little. Here is what i found worked using LINQ 2 Entity.

Say we have in your example Person <-- Developer ---- Qualifications.

If you would like to select a Developer with Qualifications included, you would do this.

var dev = (from d in context.Persons.OfType<Developer>
          where d.ID == id
          select d).FirstOfDefault();

Now lets say we have another association between Person and Address, we can also include Address into the select also using LINQ 2 Entity.

var dev = (from d in context.Persons
          where d.ID == id
          select d).FirstOfDefault();

Notice how I have included the things I needed before I converted the Type and also included again after the conversion. Both includes should now work together without any problems. I have tested these methods and they both work. I hope they work for you given you have your inheritance setup correctly.


6/16/2016 12:34:09 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow