问题
Can a class inherit from Entity Framework class and still persist back to the DB using the inherited classes mappings? I have received errors trying to derive from a 'Self-Tracking Entity' class when I try and SaveChanges stating that the Type does not have any mappings. I would have hoped since the Type was Inherited from the Entity class that it could also inherit the entity mappings somehow for this to work. Has anyone been able to get this to work?
The scenario I am trying to support is to extend the Entity object in another assembly that references the assembly containing the Entity's and mappings. Partials classes and mappings are compiled into the assembly containing the Entity objects. So I can't accomplish this through the use of partial classes.
回答1:
No it is not possible with EDMX (and self tracking entities). If you want to store derived type it must be mapped as well. If you need to add anything to generated code use your own partial part of the entity class.
Surprisingly it looks like it is possible with code-first (EFv4.1 and DbContext API) but in such case you cannot use self tracking entities. I just checked database and it is not possible with code-first as well. It silently creates TPH inheritance and derived class is mapped as an another entity.
回答2:
Unless you really need to override some of the data or default functionality, your best bet is to just extend the class instead. Since the EF classes are declared as partial
, you can create another code file and drop your custom methods or properties in that. Then, you get all the object persistence as well as your custom code.
public partial class MyEntity
{
//Extend the base object
public string FormattedName
{
get
{
return String.Format("Lookie this! {0}/{1}", this.SomeString, this.SomeInt);
}
}
}
Edit -- In response to your clarification, your best bet if you need to modify an EF class in another assembly is unfortunately to create a wrapper class that takes an Entity class as a member. You would then write all the new functionality to access the boxed Entity's public pieces. It won't give you persistence for the new properties, but you weren't getting that anyway.
来源:https://stackoverflow.com/questions/5796829/can-a-class-inherit-from-entity-framework-class-and-still-persist-back-to-the-db