Search code examples
c#entity-frameworkinheritanceentity-framework-4model

Entity framework data context does not contain a collection of my entity that uses inheritance. Why?


I am using a model with Entity Framework that takes advantage of inheritance. I have one entity for the base type called "User" and two entities that inherit from it ("Admin", and "Worker"). Here is the model:

Entity Relationship Diagram

The problem is that when I create my Entity Framework container it does not have a collection of workers or admins on it, only users.

EntityContainer context = new EntityContainer();
context.Users; // Exists.
context.Workers; // does not exist.

How can I get a collection of workers/admins and not just generic users? Likewise, how can I give my FamilyAccount entity a navigation property for Admins and Workers, not generic users?

PS - I am using the table-per-type model for my inheritance, if that matters.

.OfType seems to work well. Is there another way to actually add a navigation property for just workers or admins?


Solution

  • http://mosesofegypt.net/post/Inheritance-and-Associations-with-Entity-Framework-Part-3.aspx

    This article describes how to extend an entity and add a navigation property yourself. Scroll to the "Build Specific Department Query" header. This is what I was after, eliminating the requirement of using .OfType<Worker>().

    Now I can do familyAccount.Admins and all is good in the neighborhood.