Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving from classes generated by Entity Framework in C#

I have created an entity data model and generated a database from it.

One of the entities is called Template.

Created partial classes to extend the functionality of Template works fine.

If I create a new class and try to derive from Template, I get a runtime exception upon instantiating:

Mapping and metadata information could not be found for EntityType 'Template001'.

How can I work around this? I definitely need to inherit from the EF classes.

EDIT

Does not seem possible. If that is the case, what would be the best way to implement the following requirement: The template entity stores information about templates that each have their own code to execute. That is why I was trying to derive from the entity in the first place.

like image 568
Raheel Khan Avatar asked Mar 26 '12 18:03

Raheel Khan


2 Answers

It is not supported. You cannot derive a new type from entity and use it instead of the mapped entity type for persistence. If you want to have derived class from entity you must use mapped inheritance where every child is also mapped to the database.

like image 119
Ladislav Mrnka Avatar answered Sep 28 '22 15:09

Ladislav Mrnka


Why do you need to inherit from entity class first of all? If you want to add some simple behavior, use partial class.

Update: Based on comments, it appears that there is possibility that behavior will be extended over the time. In this case, I would recommend using composition/aggregation, not inheritance. Let the classes that need to be extended have an entity as a field. In Raheel's scenario, it would be a class called TemplateLogic with field/property of type Template.

like image 32
Sergey Sirotkin Avatar answered Sep 28 '22 15:09

Sergey Sirotkin