EF6。回滚事务后保存异常信息到数据库

EF6. Save exception information to database after rollback transaction

我需要将异常信息保存到数据库中。

SomeMethod() 
{
    try 
    {
         using(transaction = context.beginTransaction())
         {
             try 
             {
                 // here is the database error
                 await transaction.CommitAsync();
             } 
             catch(Exception e)
             {
                 await transaction.Rollback();
                 throw;
             }
         } 
    }
    catch(Exception exception) 
    {
        // Here I get the same error that was generated inside the transaction
        context.Set<LogEntity>().Add(new LogEntity(....));
        await context.SaveChangesAsync();
    } 
}

我是否正确理解上下文是与数据库的连接,并且在一个上下文中我可以执行多个事务?

据我了解,这个阶段的context处于脏状态?

发生事务错误后如何写入数据库?

As I understand it, the context in this stage is in a dirty state?

正确。 "database error" 一定发生在 SaveChanges(Async) 调用中,因此如果您在同一上下文中重复该调用,异常将再次发生。补救措施很简单:在 catch 块中使用新的上下文。

旁注:没有必要在 using 块中捕获异常。如果事务在处理之前未提交,它将被回滚。