Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework DateTime column - GetDate() value Insertion

I have a table with DateCreated and DateUpdated columns and using Entity Framework to insert/update values to the database.

I need the DateCreated column to get the SQL Server's GetDate() value on insertion only.

DateUpdated column value should always get updated with current GetDate() value on insertion and update both.

For the DateCreated column, I've set StoreGeneratedPattern="Computed" and on SQL Server table I've set default value of the column to be GetDate(), which works nicely as expected.

For the DateUpdated column I could not find a way to get the GetDate() value automatically set each time an entry is updated. This value get's set only when an entry is inserted.

Could someone shed some light on this.

like image 648
Eranga Dissanayaka Avatar asked Dec 09 '11 15:12

Eranga Dissanayaka


1 Answers

If you want DateUpdated to be set by the database, you can use a trigger to set the value to getdate(). I believe EF will also get the value set by the trigger if you set StoreGeneratedPattern="Computed" for DateUpdated.

For reference, your trigger would look something like this (you'll have to update per your table's PK):

create trigger MyTable_UpdatedTrigger
on MyTable
for update
as
begin
    update t set DateUpdated = getdate()
    from MyTable t
        join inserted i on t.Id = i.Id
end
like image 182
Jeff Ogata Avatar answered Sep 24 '22 23:09

Jeff Ogata