开发者

Entity framework : Watch changes saved on my objects

开发者 https://www.devze.com 2023-01-16 00:27 出处:网络
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.

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, Fie开发者_如何学GoldName, 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消