在.NET中嵌套事务 [英] Nested Transactions in .NET

查看:198
本文介绍了在.NET中嵌套事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能执行此相同呢? 我的理解是,这是不可能的TransactionScopes 的,但我想完成相当于一些另一种方式:

How can I perform the equivalent of this? My understanding is that this is impossible with TransactionScopes but I'd like to accomplish the equivalent in some other way:

业务逻辑类:

public bool Bar()
{
  try
  {
    using (var tsWork = new TransactionScope())
    {
      ComplicatedDataImportCode(somedata);
      FlagRecordInDatabaseAsImported(); // this is the same record that's modified in the catch
      tsWork.Complete();
      return true;
    }
    catch (DuplicateDataException err)
    {
      // if we got here, the above transaction should have rolled back,
      // so take that same record in the database and update it to "Duplicate".
      FlagSameRecordInDatabaseAsDuplicate(err.Message);
    }

    return false;
}

现在这工作正常,直到我封装了所有交易的这里面的(也许是一个集成测试,我想执行断言后回滚)。

Now this works fine, until I encapsulate all of this inside of a transaction (perhaps an integration test that I want to rollback after performing asserts).

简单的测试来证明我的观点:

Simple test to prove my point:

public void CanTest()
{
  // Arrange
  var foo = new Foo();

  using (var ts = new TransactionScope())
  {
    // Act
    var success = foo.Bar();

    // Assert
    if (success)
    {
      Assert.That(SomethingThatTestsThatTheDataWasImported);
    }
    else
    {
      Assert.That(SomethingThatTestsThatTheRecordWasMarkedAsDuplicate);
    }

    // Now that we have been able to perform our Asserts, rollback.

  }
}

最后,code。在 Foo.Bar()可以被修改,以适应解决方案,但是,code。在 ComplicatedDataImport code()不能修改这个解决方案,并因此我真正需要确保我正确地回滚失败场景。

Ultimately, the code in Foo.Bar() can be modified to accommodate a solution however, the code in ComplicatedDataImportCode() cannot be modified for this solution, and is consequently what I really need to make sure I properly rollback in the failure scenario.

此外,据我所知,TransactionScopes不能用来做这一点,根据我在这个问题一开始引用的文章。我用TransactionScopes这里说明什么,我想做的事,并在寻找实现这一功能的最好的替代方法。

Again, I understand that TransactionScopes cannot be used to do this, according to the post that I referenced at the beginning of this question. I used TransactionScopes here to indicate what I wanted to do, and am looking for the best alternative way to implement this functionality.

推荐答案

是不是这样,这必须由您正在使用的数据库管理系统来支持?

Isn't it so that this must be supported by the DBMS you're using ?

SQL Server不真正支持嵌套事务,例如,然而,与SQL Server可以使用的保存点

SQL Server doesn't really support nested transactions for instance, however, with SQL Server you can use savepoints.

我写了一篇文章几年前,在我的博客。

An article I've written some years ago on my blog.

这篇关于在.NET中嵌套事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆