Entity Framework auditing IDbCommandInterceptor

482 views Asked by At

I have a project where I am trying to perform basic auditing on my entites outside of the override SaveChanges method. I don't want to perform auditing there in the case when SaveChanges calls are wrapped in transactions. I don't want to create the audits if for some reason the transaction fails.

I was thinking about moving the auditing to the IDbCommandInterceptor NonQueryExecuted method. The issue with this is that after a Save/Update/ or Delete is executed this method is called 7 or 8 times.

Is there another place I can put the auditing code?

EDIT: I am not writing the audits in SQL so rolling back the transaction will not roll back the audit

1

There are 1 answers

0
Kirill Bestemyanov On BEST ANSWER

You can write code to wrap your auditing code into transaction. There is IEnlistmentNotification that you should use in you auditing service.

public class AuditingService: IEnlistmentNotification
{
    private bool _isCommitSucceed = false;
    private string _record;
    public AuditingService(string record)
    {
        _record = record;
        //init your audit
        Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
    }
    public void Commit(Enlistment enlistment)
    {
        //save audit record
        _isCommitSucceed = true;
        enlistment.Done();
    }
    public void InDoubt(Enlistment enlistment)
    {
        enlistment.Done();
    }
    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared();
    }
    public void Rollback(Enlistment enlistment)
    {
        if (_isCommitSucceed))
        {
            //remove auditing record that was added in commit method
        }
        enlistment.Done();
    }

}

And use:

using(var transaction = new TransactionScope())
{
   //some code that save data to db
   var auditor = new AuditingService("Save data to db");
   transaction.Complete();   
}