Extending the Entity Platform Model to Include a New Property

I am new to EF, so please excuse me if this is a noob question.

Basically, we have an EF model created using the First model for our project β€œplatform” and shared in many applications that we build on top of this platform. In some of these applications, we want to extend the classes to include additional properties without changing the model on the platform. Is this possible with EF 4 and how can I do this without modifying the .edmx file?

I noticed that the generated classes are partial, so I could create a new incomplete class with the same name to include new properties, but are there any mappings I need to take care of?

ps under normal circumstances, I would prefer to use inheritance and create a new class to store new properties, but again, I do not know how to do this with EF. Any enlightenment here would be greatly appreciated!

Many thanks,

+6
source share
3 answers

You cannot use inheritance, because as soon as the object is loaded from the data source, EF will not know about inheritance, and because of this, it will create a base type without your properties instead of a derived type with your properties. Any inheritance should be displayed in EDMX if EF should work with it.

Using a partial class will solve your problem, but:

  • All parts of a partial class must be defined in one assembly.
  • Properties from your partial part are not stored in the database
  • Properties from your partial part cannot be used in linq-to-entity queries
+20
source

EF generates partial classes. To extend MyEntity, create the MyEntity.cs file with

partial class MyEntity { public string MyExtraProperty {get;set;} } 

edit: in the same namespace as the objects you created

+7
source

I agree to add additional properties to the partial class of your objects (like you and Kaido).

Thus, you can freely add the properties you need without changing the generated classes, and if you create your model again (or update it from the database), your partial class will not be changed.

In my opinion, adding properties to partial classes of generated objects is the way to go.

+1
source

Source: https://habr.com/ru/post/888830/


All Articles