Search code examples
c#.netentity-frameworkpartial-classessql-server-2008-r2

EF partial classes and default values


Following on from an SO dicsussion here, I have implemented partial classes so as to create default datetime values for my Created and Modified database fields in a Constructor.

Now the problem is that my database has 100+ tables, and 75+ of them have the same basic structure which includes a Created and a Modified column definition.

So.. Instead of creating 75+ partial classes which I need to maintain, is there any way I can create a base class which every EF type inherits from, which inherits the default constructor to populate the DateTime values for Created and Modified?

EDIT: Worthy of note is that I am using EF 4.0


Solution

  • You can certainly specify your own base class with both EF4 and EF1, though it's a lot easier with EF4. Right click on the design surface and you should see an option to add a Code Generation Item. Select the ADO.Net entity object generator. This will a T4 file to your project (.tt extension) that specifies the template to use to generate your entity classes from the model. To specify a different base class, look inside it for a line like

    Private Function BaseTypeName(ByVal entity As EntityType, ByVal code As CodeGenerationTools) As String
        Return If(entity.BaseType Is Nothing, "EntityObject", MultiSchemaEscape(DirectCast(entity.BaseType, StructuralType), code))
    End Function
    

    Replace EntityObject with your base class. Note that if you are using this template then your base class must inherit from System.Data.Objects.DataClasses.EntityObject - you could use a POCO template instead, but this will probably be enough for you.