-->

嵌套事务范围.NET(Nested transaction scope .net)

2019-11-02 03:09发布

我使用的是SQL Server 2008 R2和尝试使用交易。

首先关于在.NET和SQL Server事务问题。 如果我有这样的事情

try {
    var transactionOption = new TransactionOptions();
    transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
    transactionOption.Timeout = TransactionManager.MaximumTimeout;

    using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
        //create question this creates a new question in the database
        Helpers.CreateQuestionBankItem(ref mappedOldNewQuestionItemGuid, missingQuestionBankItems);
        //question created

        //query database for the code of the newly inserted question, will the database give me the code since Complete has not been called as yet?    



        scope.Complete();
    }
}
catch (Exception ex) {
    throw;
}

//query database for the code of the newly inserted question,  will the database give me the code since Complete has been called as now?    

在这一点,我应该调用数据库,要求新插入的问题的代码。 现在我的第二个问题,我问之前,我发现这个链接嵌套事务 。 在上面的链接我想要的光还问,如果我有这样的事情

try {
    var transactionOption = new TransactionOptions();
    transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
    transactionOption.Timeout = TransactionManager.MaximumTimeout;

    using (var outerscope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
        try {
            var transactionOption = new TransactionOptions();
            transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
            transactionOption.Timeout = TransactionManager.MaximumTimeout;

            using (var innerscope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
                //create question this creates a new question in the database
                Helpers.CreateQuestionBankItem(ref mappedOldNewQuestionItemGuid, missingQuestionBankItems);
                //question created

                //query database for the code of the newly inserted question, will the database give me the code since Complete has not been called as yet?    

                innerscope.Complete();
            }
        }
        catch (Exception ex) {
        }

        //query database for the code of the newly inserted question,  will the database give me the code since Complete has been called as now?    

        outerscope.Complete();
    }
}
catch (Exception ex) {
    throw;
}

如果我的innerscope完成后,将查询的SQL Server给我新创建问题的代码。

如果内部范围抛出一个异常,我狼吞虎咽起来,将外部范围也处理掉,会发生什么?

是否调用innerscope.Complete()完成内心的范围是什么?

Answer 1:

如果你想从一个失败的事务上下文中恢复,你需要使用事务保存点 。 不幸的是,管理System.Transaction对保存点的支持。 不仅如此,但你将无法使用保存点,甚至直接,如果你使用的交易范围,因为交易范围将升级为分布式事务和保存点不分布式环境中工作。

您可以使用,而不是特定于平台SqlTransaction它支持Save()的保存点。 见异常处理和嵌套事务的事务感知异常处理的例子。



文章来源: Nested transaction scope .net