Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Entity Framework Model to include new property

I'm new to EF so please excuse me if this is a noob question.

Basically, we have a EF model set up using Model First for our 'platform' project and is shared across many applications which 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 in the platform. Is this possible with EF 4 and how would I be able to do it without modifying the .edmx file?

I notice that the generated classes are all partial so potentially I could create a new partial class with the same name to include the new properties but is there any mappings that need to be taken care of?

p.s. under normal circumstances I'd have preferred to use inheritance and create a new class to hold the new properties instead but again, I don't know how to do that with EF.. any enlightenment here will be much appreciated!

Many thanks,

like image 354
theburningmonk Avatar asked May 23 '11 15:05

theburningmonk


2 Answers

You cannot use inheritance because once entity is loaded from the data source EF will not know about inheritance and because of that it will instantiate base type without your properties instead of derived type with your properties. Any inheritance must be mapped in EDMX if EF have to work with it.

Using partial class will solve your problem but:

  • All parts of partial class must be defined in the same assembly
  • Properties from your partial part are not persisted to the database
  • Properties from your partial part cannot be used in linq-to-entities queries
like image 76
Ladislav Mrnka Avatar answered Oct 04 '22 20:10

Ladislav Mrnka


EF generates partial classes. So to extend MyEntity, create a MyEntity.cs file with

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

edit: in the same namespace as your generated entities

like image 39
Kaido Avatar answered Oct 04 '22 21:10

Kaido