嵌套事务范围.net

时间:2013-04-25 12:20:00

标签: c# sql-server transactions nested-transactions

我正在使用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?    

我应该在何时调用数据库来询问新插入问题的代码。现在我的第二个问题,在我问之前我找到了这个链接Nested Transaction。根据上述链接,我还想问,如果我有这样的东西

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()是否完成了内部范围?

1 个答案:

答案 0 :(得分:3)

如果要从事务上下文中的故障中恢复,则需要使用transaction savepoints。很遗憾,托管System.Transaction不支持保存点。不仅如此,如果您使用事务范围,您甚至无法直接使用保存点,因为事务范围将升级为分布式事务,而保存点在分布式上下文中不起作用。

您可以使用支持SqlTransaction的特定平台Save()作为保存点。有关事务感知异常处理的示例,请参阅Exception Handling and Nested Transactions