开发者

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 framework data context does not contain a collection of my entity that uses inheritance. Why?

(source: codetunnel.com)

The problem is that when I create my Entity Framework container it doe开发者_如何学JAVAs 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?

Thanks in advance!

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?


Yes, it's the behaviour of EF. If you want to navigate to Admin and Worker, you can do the following :

var admins = context.Users.OfType<Admin>();
var workers = context.Users.OfType<Worker>();


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.


Table-per-Type (TPT) Inheritance involves storing all properties from the base type in a single table. Table-per-Concrete Type (TPC) Inheritance involves storing the data for each type in a completely separate table with no foreign key constraints between them.

If you would like separate tables for Admins and Workers then you should probably be using TPC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜