views:

24

answers:

1

Hi,

For my project, I have to log all changes made on my objects, through the entity framework. This consists just to register which fields have been edited on which table at which time.

Roughly, put changes in a table with this kind of structure: IDEvent, EventDate, TableName, RowID, FieldName, OldValue, NewValue

If there is multiple changes, several rows will be inserted.

It already works for 90% of my cases, I'm listening the SavingChanges event of the ObjectContext

My only problem: In the case of an add, my primary keys that are generated by SQL(IDENTITY), are not present at this moment(logic) on the SavingChanges event, because it's not already stored in the DB, and the problem is that I really need it(To fill my RowID in my table)

So, do you have an idea how to do this? I didn't found any "ChangesSaved" event. An idea of workaround?

Thank you!

+1  A: 

You will not be able to do this in SavingChanges event. I think you can create your own wrapper for ObjectContext and implement your own logic in wrapper method for SaveChanges. Logic should be like

public class MyContextWrapper : IDisposable
{
  private ObjectContext _context;

  public void SaveChanges()
  {
    // Detect changes but do not accept them
    _context.SaveChanges(SaveOptions.DetectChangesBeforeSave); // SaveChanges(false) in .NET 3.5 SP1

    // TODO audit trail

    // Audit is completed so accept changes
    _context.AcceptAllChanges();
  }

}

You should also add TransactionScope to your new SaveChanges.

Ladislav Mrnka
Yes it's almost what I've for the moment: In fact I've a ChangeListener that is registred to all SaveChanges, when it see it's an "add" change, it put the object to a List of object to handle. And after I've made my _context.SaveChanges(), I ask for a myListener.HandleInsertedObject()
J4N