2
我想覆盖Entity Framework的SaveChanges()
方法来保存审计信息。我开始与以下内容:我有EF ObjectStateEntry OriginalValues包含CurrentValues
public override int SaveChanges()
{
ChangeTracker.DetectChanges();
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
List<ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager.GetObjectStateEntries(
EntityState.Added
| EntityState.Modified
| EntityState.Deleted).ToList();
foreach (ObjectStateEntry entry in objectStateEntryList)
{
if (!entry.IsRelationship)
{
//Code that checks and records which entity (table) is being worked with
...
foreach (string propertyName in entry.GetModifiedProperties())
{
DbDataRecord original = entry.OriginalValues;
string oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();
CurrentValueRecord current = entry.CurrentValues;
string newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();
if (oldValue != newValue)
{
AuditEntityField field = new AuditEntityField
{
FieldName = propertyName,
OldValue = oldValue,
NewValue = newValue,
Timestamp = auditEntity.Timestamp
};
auditEntity.AuditEntityField.Add(field);
}
}
}
}
}
问题是价值观我entry.OriginalValues
领取并entry.CurrentValues
永远是新的更新值:
有同样的问题,但不是这个错误?不能想象,我们将不得不首先检查每个属性,然后决定如果我们保存或不。..?! :/ – mxii 2016-03-15 07:56:19
在第一种方法中,EF不知道有关实体的原始值的任何信息。如果原始值与当前值相同,似乎是合乎逻辑的。检查http://stackoverflow.com/questions/9588352/entity-framework-dbcontext-savechanges-originalvalue-incorrect – 2016-06-13 12:35:07