2015-02-05 52 views
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永远是新的更新值:

Audit Entity State

回答

1

的问题已被发现:

public ActionResult Edit(Branch branch) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Entry(branch).State = EntityState.Modified; 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(branch); 
} 

以上述方式保存更新似乎会导致ChangeTracker不能提取旧值。我通过简单地使用ViewModels来解决所有需要的更新:

public ActionResult Edit(BranchViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     Branch branch = db.Branch.Find(model.BranchId); 

     if (branch.BranchName != model.BranchName) 
     { 
      branch.BranchName = model.BranchName; 
      db.SaveChanges(); 
     } 
     return RedirectToAction("Index"); 
    } 
    return View(model); 
} 
+1

有同样的问题,但不是这个错误?不能想象,我们将不得不首先检查每个属性,然后决定如果我们保存或不。..?! :/ – mxii 2016-03-15 07:56:19

+0

在第一种方法中,EF不知道有关实体的原始值的任何信息。如果原始值与当前值相同,似乎是合乎逻辑的。检查http://stackoverflow.com/questions/9588352/entity-framework-dbcontext-savechanges-originalvalue-incorrect – 2016-06-13 12:35:07