4

I am trying to override Entity Framework's SaveChanges() method to save auditing information. I begin with the following:

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);
                }
            }
        }
    }
}

Problem I'm having is that the values I get in entry.OriginalValues and in entry.CurrentValues is always the new updated value:

Audit Entity State

Carel
  • 1,849
  • 8
  • 28
  • 58

3 Answers3

1

The problem has been found:

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

Saving an update in the above way seems to cause the ChangeTracker to not pick up the old values. I fixed this by simply making use of ViewModels for all the required updates:

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);
}
Carel
  • 1,849
  • 8
  • 28
  • 58
  • 1
    having the same problem, but isnt this a bug? cant imagine that we'll have to check each property first and decide then if we save or not .. ?! :/ – slaesh Mar 15 '16 at 07:56
  • In the first method, EF does not know anything about original value of the entity. It seems is is logical if original values are as same as current value. Check http://stackoverflow.com/questions/9588352/entity-framework-dbcontext-savechanges-originalvalue-incorrect – Afshar Mohebi Jun 13 '16 at 12:35
0

To get a copy of the old values from the database without updating the EF entity you can use

context.Entry(yourEntity).GetDatabaseValues().ToObject()

or

yourEntity.GetDatabaseValues().ToObject()

Caution: this does instigate a database call.

jmdon
  • 877
  • 8
  • 17
0

The easiest way to do for me was:

var cadastralAreaDb = await _context.CadastralAreas.FindAsync(id).ConfigureAwait(false);

  var audit = new Audit
  {
     CreatedBy = "Edi"
   };

_context.Entry(cadastralAreaDb).CurrentValues.SetValues(cadastralArea);
await _context.SaveChangesAsync(audit).ConfigureAwait(false);

This is tested in ASP NET Core 3.1

Edi
  • 804
  • 9
  • 19