如何创建/更新EF代码第一次一个领域上次更改 [英] How to create/update a LastModified field in EF Code First
本文介绍了如何创建/更新EF代码第一次一个领域上次更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想补充一点,当存储记录保存到磁盘当前日期时间的列。什么是完成这一任务的最佳方式?
I want to add a column that stores the current DateTime when a record is saved to disk. What would be the best way to accomplish this?
我知道这不是一个非常复杂的问题,但我不知道是否有任何的最佳做法或会简化任务EF的任何特征。
例如:
I know it's not a very complex problem, but I wondered if there is any best practice or any feature of EF that would simplify the task. For example:
- 有没有什么办法,包括对表类中该领域的逻辑,因此,它的自动更新每当它保存到磁盘上?
- 是否有任何情况下,当一个对象被修改或保存?
推荐答案
一个选项是创建存储库层和实现自己的SaveChanges
one option would be to create repository layer and implement your own SaveChanges
public void SaveChanges()
{
foreach (var entry in Context.ChangeTracker.Entries<ICreatedAt>().Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime)))
entry.Entity.CreatedAt = DateTime.Now;
foreach (var entry in Context.ChangeTracker.Entries<ICreatedBy>().Where(x => x.State == EntityState.Added && x.Entity.CreatedBy == null))
entry.Entity.CreatedBy = ContextManager.CurrentUser;
foreach (var entry in Context.ChangeTracker.Entries<IModifiedAt>().Where(x => x.State == EntityState.Modified))
entry.Entity.ModifiedAt = DateTime.Now;
foreach (var entry in Context.ChangeTracker.Entries<IModifiedBy>().Where(x => x.State == EntityState.Modified))
entry.Entity.ModifiedBy = ContextManager.CurrentUser;
Context.SaveChanges();
}
这篇关于如何创建/更新EF代码第一次一个领域上次更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文