实体框架DateTime列 - GetDate()值插入 [英] Entity Framework DateTime column - GetDate() value Insertion
问题描述
我有一个表,其中包含 DateCreated
和 DateUpdated
列,并使用Entity Framework将值更新到数据库。
我需要 DateCreated
列来获取SQL Server的 GetDate() code>仅在插入时的值。
DateUpdated
列值应始终使用当前 GetDate()
插入和更新的值。
对于 DateCreated
列,我已经设置了 StoreGeneratedPattern =Computed
,而在SQL Server表上,我设置了列的默认值为GetDate(),它按照预期工作很好。
对于 DateUpdated
列,我找不到一种方法来获取 GetDate()每次更新一个条目时,会自动设置
值。这个值只有在插入条目时才设置。
有人可以看出这一点。
如果您想要数据库设置 DateUpdated
,可以使用触发器将值设置为 getdate ()
。我相信如果您为 DateUpdated
设置 StoreGeneratedPattern =Computed
,则EF也将获取触发器设置的值。 / p>
为了参考,你的触发器看起来像这样(你必须更新你的表的PK):
创建触发器MyTable_UpdatedTrigger
在MyTable
更新
作为
开始
更新t set DateUpdated = getdate()
从MyTable t
连接插入我在t.Id = i.Id
结束
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
这篇关于实体框架DateTime列 - GetDate()值插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!