如何在不中止交易的情况下不完成TransactionScope?

时间:2017-10-23 10:21:37

标签: c# .net transactions transactionscope

[TestMethod]
public void NestedTSWithFailure()
{
    // DataContext is a subclass of DbContext
    DataContext context = new DataContext();
    context.Database.Initialize(false);

    using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(20) }))
    {
        for (int i = 0; i < 5; i++)
        {
            List<TrackAndTraceEvent> eventsForShipment = context.TrackAndTraceEvents.ToList();

            try
            {
                using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(20) }))
                {
                    // Do Something.
                    if (i == 2)
                    {
                        // Artificial error causing the scope to not complete
                        throw new Exception("");
                    }
                    scope2.Complete();
                }
            }
            catch(Exception ex)
            {

            }
        }
    }
}

(TestMethod复制我遇到的问题)

所以在我的应用程序中,我已经嵌套了TransactionScopes,内部的那个继承了外部的事务。

现在当内部范围出错并且没有完成时会出现问题。它将Transaction本身置于Aborted状态,因此下次我尝试访问该事务(外部作用域)中的数据库时,会抛出上述错误:

System.Data.EntityException: The underlying provider failed on Open. ---> System.Transactions.TransactionException: The operation is not valid for the state of the transaction.

问题:有没有办法可以在不破坏交易的情况下回滚(或者只是不完整)内部范围?

这样做的目的是我有一个我需要测试的应用程序。我写了所以所有的测试都在TransactionScope中完成,因为我不想要任何提交,但是应用程序本身在 try / catch 块中使用事务范围对于循环,所以当它进入 catch 块然后进入下一个 for 循环并尝试获取数据时会发生此错误。 它不是应用程序运行时的问题,因为每个作用域都有自己的事务,但在测试中,它会失败。

0 个答案:

没有答案
相关问题