在实体管理器自动生成的时间戳 [英] Autogenerated timestamp in Entity Manager
问题描述
我有一个WPF DataGrid中绑定到其他实体(实体框架4 +)。
I have a WPF DataGrid bound to some entities (Entity Framework 4+).
然后用户编辑DataGrid和presses保存。然后将数据保存回MS SQL Server 2008中使用的SaveChanges()
。嗯......现在,我想有自动时间戳,它存储了最后一次修改的时间,会自动更新。
User then edits the DataGrid and presses SAVE. Data is then saved back to MS SQL Server 2008 using SaveChanges()
. Well... now, I would like to have AUTOMATIC timestamp which stores the time of the last change and updates itself automatically.
大家好,这可能吗?怎么样?
Guys, is it possible? How?
感谢您,詹姆斯
推荐答案
要实现这一目标最简单的方法是在数据库级别上:
The easiest solution to achieve this is on the database level:
- 用于存储你的
的DateTime
值在表中创建一个新列。 - 创建数据库触发器设置列中为每个插入或更新表。
- 地图新列属性在实体
- 设置
StoreGeneratedPattern
新属性已计算
所以在数据库中生成的值是正确更新到您的连接每次插入或更新后的实体。
- Create a new column in the table for storing your
DateTime
value. - Create database trigger to set the column for each insert or update to the table.
- Map the new column as property in your entity
- Set
StoreGeneratedPattern
for the new property toComputed
so the value generated in the database is correctly updated to your attached entity after each insert or update.
如果你不喜欢,你必须在被覆盖的SaveChanges的做手工触发,你发现将被插入或更新的所有实体,并设置列:
If you don't like the trigger you must do it manually in overriden SaveChanges where you find all entities which will be inserted or updated and set the column:
public override int SaveChanges(SaveOptions options)
{
var entities = ObjectStateManger.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
.Select(e => e.Entity)
.OfType<YourEntityType>();
DateTime now = DateTime.Now;
foreach(var entity in entities)
{
entity.Updated = now;
}
return base.SaveChanges(options);
}
这篇关于在实体管理器自动生成的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!