Reputation: 4094
public override saveChanges(){
var changeList = tracker.detectChange();
foreach(var change in changeList){
switch(change.state){
case ADD: ...
case MODIFIED: ...
}
}
base.saveChanges();
}
I have the above code structure (only pseudo code for illustrating idea) of creating audit trail when save changes.
The only problem is that, I cannot get the newly added record ID as saveChanges
has not yet been called, however if I call saveChanges
ahead, then the tracker could not track the changes as ALL state of the entries will become unchanged
!
So how can I still track the changes while getting the new record ID ?
EDITED
Reason why I have to get the new record ID, as you may guess, is to save an audit trail record in DB. For some reason, it has to be an XML document which stores the entity's ID, original value & new value (and some other stuff which is out of concern).
Say for a newly added "Item" in Item table in DB, I have to store a new audit trail record which at least showing this new "Item" 's ID, original value (which is null), and new value.
Upvotes: 0
Views: 538
Reputation: 1126
The changed entities can be added to separate lists according to their state before the method saveChanges
is called.
After saveChanges
all entities would be updated with new Ids and the corresponding lists can be used to generate the audit logs.
public override saveChanges(){
// gather audit data
initialize List<Entity> addedEntities, modifiedEntities, deletedEntities
var changeList = tracker.detectChange();
foreach(var change in changeList){
switch(change.state){
case ADD: add to addedEntities
case MODIFIED: add to modifiedEntities
}
}
base.saveChanges();
performAudit(addedEntities, modifiedEntities, deletedEntities);
}
function performAudit(...){
generateXML(...);
saveToDB(...);
sendEmail(...);
}
Note: I have not tested if deletedEntities
would still be valid, but they can anyway be audited before saveChanges as they already have an Id. But I hope you get an idea on how to solve your problem.
Upvotes: 3