Question

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

Was it helpful?

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.

OTHER TIPS

You can certainly tell EF to use a base class for your entities (it's right in the designer as a property for the entity)...but if you want to make sure of the default value for this field, perhaps you could hook into the two events on your ObjectContext SavingChanges and ObjectMaterialized.

http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savingchanges.aspx

http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.objectmaterialized.aspx

You could use these opportunities to inject the default value(s) that you want to use. So in your SavingChanges handler, for example, you could check the ObjectStateManager on the context to see if the state of the relevant entity is EntityState.Added, then set the Created and Modified dates as desired.

Alternatively, as suggested, is there a reason the default value for the column in SQL Server can't just be GetDate()? (Assuming you're using SQL Server)....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top