Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Default column value from DataBase in Entity Framework?

Implementing the OnCreated event for the entity is the solution I have found. I had a Guid property that I wanted to be populated. By default it was being populated with all zeros (00000-0000-00000-etc). By adding the following to my partial class of the entity I was able to deal with the issue.

partial void OnCreated()
{
    Guid = Guid.NewGuid();
}

StoreGeneratedPattern = "Computed" is not the same as a default value, because this property would be updated EVERY TIME with the default value in the database.. meaning it is impossible to update it manually.


You can set the StoreGeneratedPattern to Identity, in which case EF reads the value returned from the database after executing the INSERT statement. The problem with this approach is that the next time the XML mapping is generated, your change will be lost.

Another way to do it is to set the value yourself in your code to DateTime.UtcNow. You could set this in your entity's constructor (define a new constructor if necessary), or you could set it in your own event handler for your context's SavingChanges event (see How to: Execute Business Logic When Saving Changes (Entity Framework) for an example of handling the SavingChanges event).


A problem with setting StoreGeneratedPattern = "Computed" or "Identity" is that they do not allow the client to ever provide a value. Running into this issue on inserts but also for updates.

Seems like another option or two is needed for StoreGeneratedPattern so the database can at least see the user provided values but override it if need be. This would allow any existing DB insert or update triggers that update one field based on another field to work. For instance a DB trigger on an update might update the modified timestamp only if one is not provided and only if certain fields were updated.

Perhaps the column extended attributes feature in SQL Server could be used to set that field automatically during extraction so we don't end up editing XML files.


There is another solution suggested in this post by using a partial class and a method in the constructor to set the values.

How to use the default Entity Framework and default date values