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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With