可能重复:
Entity Framework DbContext SaveChanges() OriginalValue Incorrect
我发现以下内容对我的需求来说非常简单:http://jmdority.wordpress.com/2011/07/20/using-entity-framework-4-1-dbcontext-change-tracking-for-audit-logging/
我正在使用MVC3和Ninject和EF。我正在我的具体EFDBContext类中实现上述解决方案。修改实体的部分是检查原始值和当前值,以确定应将哪些值写入审计表。问题是我看到原始值作为发布的数据,因此当检查时似乎没有任何变化。
else if (dbEntry.State == System.Data.EntityState.Modified)
{
foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
{
string original = dbEntry.OriginalValues.GetValue<object>(propertyName).ToString();
string current = dbEntry.CurrentValues.GetValue<object>(propertyName).ToString();
// For updates, we only want to capture the columns that actually changed
if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)))
{
result.Add(new TransactionHistory()
{
//TransactionHistoryID = Guid.NewGuid(),
TransactionTypeID = 2,
TableName = tableName,
FieldName = propertyName,
RecordPK = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(),
OldValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(),
NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString(),
TransactionBy = userId,
TransactionDate = changeTime,
TransactionApplication = "Galactus"
});
}
}
}
当我单步执行调试器时,我可以看到字符串原始字符串和字符串当前是相同的(两个新数据都已发布)。
我不确定这里没有被正确跟踪。我的存储库以这种方式调用它。
public void Edit(T entity, string userID)
{
context.Entry<T>(entity).State = System.Data.EntityState.Modified;
context.SaveChanges(userID);
}
使用saveChanges浏览列表。
public int SaveChanges(string userId)
{
// Get all Added/Deleted/Modified entities (not Unmodified or Detached)
foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == System.Data.EntityState.Added || p.State == System.Data.EntityState.Deleted || p.State == System.Data.EntityState.Modified))
{
// For each changed record, get the audit record entries and add them
foreach (TransactionHistory x in GetAuditRecordsForChange(ent, userId))
{
this.TransactionHistories.Add(x);
}
}
// Call the original SaveChanges(), which will save both the changes made and the audit records
return base.SaveChanges();
}
知道为什么我没有在发布的数据之前获得原始值吗?