实体框架审计IDbCommandInterceptor

本文关键字:IDbCommandInterceptor 审计 框架 实体 | 更新日期: 2023-09-27 17:54:34

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

我正在考虑将审计移动到IDbCommandInterceptor nonqueryperformed方法。这样做的问题是,在执行保存/更新/删除后,该方法被调用7或8次。

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

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

实体框架审计IDbCommandInterceptor

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

相关文章:
  • 没有找到相关文章