Code-Generated Base Entity Class
Hey team,
Is there a way to specify the base-class that the generated entities inherit when the code is generated?
I'm thinking of creating a base-class that contains common functionality, and want to have the generated classes derrive from that instead of System.Data.Objects.Entity. My base-class will of course extend System.Data.Objects.Entity. :)
Thanks!
Technically we don't support abstract base classes, but it is possible to do something like this. In your CSDL file you can create an entity type which all of your other entity types inherit from. That type can contain properties which exist on all of your other entities, in which case when you write your map file you will need to map not only the added properties on each entity but also the ones contributed by the base type. The code generator will output classes for each of your entities as well as the common base type which inherits from Entity. You can add behavior to the partial base class which will then be inherited by the other classes as well.
I've done this in a sample model of my own so I know it works. What I haven't tried is creating a base type that doesn't contribute any properties--only behaviors. I'm not sure that will work, but it's probably worth a try.
- Danny
Well, because we don't officially support abstract entity types, it's very possible that you will run into some limitations. For instance, I'm fairly certain that we always require entity types to specify which of their properties make up the key. So if you define a base entity type it will likely have to include a key property (which would mean that all of your types which inherit from it will have that key as well).
In the sample app where I have created an abstract base type of sorts, I actually used guids for IDs for all of my types (even though they are awful for indexing) so it was OK for my scenario. When I mapped my model to the database I separately mapped each of the types immediately my base type to a different table in the database (and then used table-per-hierarchy inheritance to put all the types below that into those tables).
So, to really support a specialized entity class that sits between entity and all the rest of your types and provides additional behavior I think you would either need to edit the generated code (UGGG!) or wait for better abstract type support. This is something we'll give some thought to.
- Danny