实体框架审核IDbCommandInterceptor

时间:2015-06-09 17:09:02

标签: c# .net entity-framework audit

我有一个项目,我试图在覆盖SaveChanges方法之外对我的entites执行基本审计。在SaveChanges调用包含在事务中的情况下,我不想在那里执行审计。如果由于某种原因交易失败,我不想创建审核。

我正在考虑将审计转移到IDbCommandInterceptor NonQueryExecuted方法。这个问题是在执行Save / Update /或Delete之后,此方法被调用7或8次。

我还有其他地方可以提供审核代码吗?

编辑: 我不是在SQL中编写审计,因此回滚事务不会回滚审计

1 个答案:

答案 0 :(得分:0)

您可以编写代码将审计代码包装到事务中。 您应该在审核服务中使用IEnlistmentNotification

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();
    }

}

并使用:

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