Entity Framework DateTime column - GetDate() value Insertion

[亡魂溺海] 提交于 2020-01-01 09:21:46

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/8447865/entity-framework-datetime-column-getdate-value-insertion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!