Entity Framework 审计 IDbCommandInterceptor

Entity Framework auditing IDbCommandInterceptor

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

我正在考虑将审核移至 IDbCommandInterceptor NonQueryExecuted 方法。问题在于,在执行 Save/Update/ 或 Delete 后,此方法将被调用 7 或 8 次。

还有别的地方可以放审计代码吗?

编辑: 我没有在 SQL 中编写审计,所以回滚事务不会回滚审计

您可以编写代码将您的审计代码包装到事务中。 您应该在审计服务中使用 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();   
}