I think there is no way to get the ID of a new inserted record in the SavingChanges
event since the event is simply called before the database gets touched at all and the ID is created. Unfortunately there is no SavedChanges
event which gets called after the data are saved.
A possible option might be to leverage the fact that one of the overloads of the ObjectContext's SaveChanges
method is virtual
(or overridable
in VB), namely:
public virtual int SaveChanges(SaveOptions options)
(Note: It's virtual only in EF 4, not in the earlier version! And only this overload is virtual, the other two overloads of SaveChanges are not!)
So you could override this method in your model's ObjectContext. In this overridden method you call SaveChanges of the base class and after that your new entities should have the created IDs from the database which you could log then.
(It's just a rough idea, I never tested or used this virtual overload. I've built a similar logging mechanism in SavingChanges as you're just implementing and had the same problem. But this was in EF 3.5 where this virtual method didn't exist yet. Finally I had logged Inserts only at the important places after calling SaveChanges, but that wasn't then "generic" of course. Perhaps the new virtual method is a good chance to improve that now.)
Edit
A bit more precise what I meant (in C# syntax):
public partial class MyEntitiesContext : ObjectContext
{
// ...
public override int SaveChanges(SaveOptions options)
{
// Log something BEFORE entities are stored in DB
int result = base.SaveChanges(options);
// Log something AFTER entities are stored in DB, especially new entities
// with auto-incrementing identity key which have been inserted in the DB
// should have the final primary key value now
return result;
}
// ...
}
Important is to call base.SaveChanges(options)
. (Calling only SaveChanges(options)
without base.
ends with a StackOverflow of course.)