Cannot Audit on Insert Entity Framework.I am stuck can you help?
it's my third day on this and driving me crazy.
Need to Audit whenever I do I an insert obviosly hooking to SaveChanges is no good to me as I need the newly GeneratedID that you get when you add a new record
I have overriden SaveChanges and there I can now get the newly added entries with the primary 开发者_运维技巧key.
My problem lies that I now have a newLog to insert and I need to call SaveChanges again.
Either I end up in an infinite loop or I insert the record twice.
How do you audit an insert if you need the primary key of your newly inserted object eg(CustomerId)
public override int SaveChanges(SaveOptions options)
{
int changes = base.SaveChanges(SaveOptions.DetectChangesBeforeSave);
IEnumerable<ObjectStateEntry> entries = Context.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
foreach (ObjectStateEntry entry in entries)
{
var auditLog=CreateAuditLog(Entry);
}
//Because I have saved I now got the new Id. I now need to save the newly created log and therefore
//I call save again but now this will save again all the previous stuff too or get in a infinite loop
//Is there a way I could just save the newly added stuff what is the workaround?
base.SaveChanges();
return changes;
}
How can audit on insert? any example?
Do you have to do it in the code?
Why not use a trigger in the database and copy the record over into an audit table?
An alternative might be to create a Dictionary<T,bool>
to hold the audited items.
Once you've audited the item, set the key (bool) to true, to signify it has been audited.
Or another option is to instead of saving the audit immediately, persist it into some other store (in memory, cache, session, etc).
Then depending on what type of application you are using, you could commit these audited items into the database at the end of the "request".
I'm just throwing ideas around here - but i still believe a trigger would be the easiest/safest thing to do here.
I don't know what your audit log looks like, but if it has a reference to Entry, can't you CreateAuditLog(Entry) before calling base.SaveChanges(), and the IDs should all work out.
I think you might want to try something a little different:
Create another class that manages saving your changes and saving your audit log like the following (think of this is sort of pseudo code--it isn't complete, but should give u an idea):
public void Save(Context context)
{
using (Transaction scope = new TransactionScope)
{
context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
auditContext = new MyAuditContext();
var auditLog=CreateAuditLog(Entry);
myAudtContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);
scope.Complete();
context.AcceptChanges();
myAuditContext.AcceptChanges()
}
}
A bit late in the game but I came across this post as I had the same problem. Calling the ObjectStateEntry.AcceptChanges
method worked for me. MSDN article here
精彩评论