代码之家  ›  专栏  ›  技术社区  ›  TheVillageIdiot

使用具有亚音速的事务

  •  7
  • TheVillageIdiot  · 技术社区  · 6 年前

    在我的Web应用程序中,我必须对用户操作进行审计。因此,每当用户执行某个操作时,我都会更新执行该操作的对象,并保留该操作的审计跟踪。

    现在,如果我先修改对象,然后更新审计跟踪,但是审计跟踪失败了,那又是什么?

    显然,我需要回滚对修改对象的更改。我可以在简单的应用程序中使用SQL事务,但我正在使用Subsonic与DB进行对话。我如何处理这种情况?

    3 回复  |  直到 6 年前
        1
  •  10
  •   kevinw    16 年前

    类似:

    Using ts As New System.Transactions.TransactionScope()
      Using sharedConnectionScope As New SubSonic.SharedDbConnectionScope()
    
    ' Do your individual saves here
    
    ' If all OK
          ts.Complete()
    
       End Using
    End Using
    
        2
  •  14
  •   Ben Straub    8 年前

    这个 answer 由给定 @Kevinw 很好。我发布这篇文章只是为了翻译他的答案。我不使用注释,因为它不会格式化代码:)我还使用try/catch来确定事务是应该完成还是应该回滚。

    using (System.Transactions.TransactionScope ts = new TransactionScope())
    {
        using (SharedDbConnectionScope scs = new SharedDbConnectionScope())
        {
            try
            {
                //do your stuff like saving multiple objects etc. here 
    
                //everything should be completed nicely before you reach this
                //line if not throw exception and don't reach to line below
                ts.Complete();
            }
            catch (Exception ex)
            {
                //ts.Dispose(); //Don't need this as using will take care of it.
                //Do stuff with exception or throw it to caller
            }
        }
    }
    
        3
  •  1
  •   EJP    11 年前

    不。如果我把 SharedDbConnectionScope 在更改之外,以前可以在数据库中看到 ts.Complete() . 把它放进去会阻塞服务器,直到操作完成。