开发者

How to save derived type (TPT) in Entity Framework?

I have problems with saving derived type (TPT) with Entity Framework to database.

Let's say I have base entity Animal and derived type Dog.

I want to save Dog entity.

I thought that I could do it like contex.AddToDogs(), but contex contain only base entity - A开发者_StackOverflownimal. So I can only save Animal object - contex.AddToAnimals().

I have also tried with contex.AddObject("Animals", dogInstance), but I get the following error:

The member with identity 'NavigationProperty' does not exist in the metadata collection.

But I have add EntityReference to the "NavigationProperty".

So how to save derived type in EF?


The answer is contex.AddObject("Animals", dogInstance).

Originally I got error on this, but error just says NOT the navigation property name is wrong, but the Entity Set Name is wrong. And it really was. So I fix it and now saving is working properly (Dog is saved to the animal and the Dog table).


If there is no dog entity you will not have a AddToDogs() method no matter what references you add, EF doesn't know how to automatically map derived types to entities. You can either create a function that maps one object to another or use a tool like AutoMapper

If I'm taking your question too literally and you are taking a code-first approach then for an explanation of inheritance and association in EF look at this

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜