我正在使用IPreUpdateEventListener
进行审核。我的解决方案正如Ayende Rahien所说here。像这样:
public bool OnPreUpdate(PreUpdateEvent @event)
{
var audit = @event.Entity as IHaveAuditInformation;
if (audit == null)
return false;
var time = DateTime.Now;
var name = WindowsIdentity.GetCurrent().Name;
Set(@event.Persister, @event.State, "UpdatedAt", time);
Set(@event.Persister, @event.State, "UpdatedBy", name);
audit.UpdatedAt = time;
audit.UpdatedBy = name;
return false;
}
我的问题是我必须将audit.UpdatedAt = time;
设置为在我的实体中具有值,但它会使对象变脏并导致对数据库的更多更新。我需要我的对象中的新值,但不希望重复更新。有什么办法吗?
答案 0 :(得分:1)
这不应该导致两次更新;其他事情正在发生。问题可能是数据库UpdatedAt字段分辨率与.NET DateTime.Now分辨率不同。我的代码与您的代码几乎完全相同,但我使用此方法来创建时间戳:
/// <summary>
/// Return a DateTime with millisecond resolution to be used as the timestamp. This is needed so that DateTime of an existing instance
/// will equal one that has been persisted and returned from the database. Without this, the times differ due to different resolutions.
/// </summary>
/// <returns></returns>
private static DateTime GetTime()
{
var now = DateTime.Now;
var ts = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, DateTimeKind.Local);
return ts;
}