Entity Framework 4 - Inheritance
In Entity Framework 4.0 it’s possible to model objects with inheritance in several different ways. This post goes into a multi-table layout. The following diagram is assumed for examples:
A database layout for this can look like:
Person ----- Id PK Name Address Student ------ PersonID PK StudentNumber Teacher ------ PersonID PK Subject
When you generate an .edmx file with Visual Studio 2010 based on this table layout, you end up with these 3 tables mapped as 3 classes. The inheritance hasn’t been detected/modeled, instead there are 1 to 0..1 associations.
When you’re trying to use .OfType() to retrieve only the students, it fails with this exception:
DbOfTypeExpression requires an expression argument with a polymorphic result type that is compatible with the type argument.
The solution is to model the inheritance, but the steps to do that need to be taken in a very specific order to avoid problems.
-
You need to make sure the entity’s primary keys all have the same name, it doesn’t matter how they’re called in the database, but the entity name has to be equal.
-
Add the “Inheritance” shape from the Toolbox, and drag it from Student to Person and from Teacher to Person.
-
Now remove the primary key property on the Student and Teacher entities, otherwise the generated objects will get the property from 2 sources, which doesn’t work.
-
Go to the mapping details of Student and Teacher (right-click -> Table mapping). The mapping for the primary key is now empty here, because you removed the primary key in the previous step. From the drop down select the primary key, this time it’s the property from the base class.
-
Remove the navigation properties from person to student/teacher and back, they no longer serve a purpose because a student is a person.
If someone knows a faster/better way to get this done, please comment.