嵌套事务作用域
本文关键字:作用域 嵌套事务 | 更新日期: 2023-09-27 18:10:56
我正在使用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;
}
如果我的内层作用域完成,查询SQL Server会给我新创建的问题的代码吗?
如果内部作用域抛出异常而我处理掉它,外部作用域也会被处理掉吗?
调用innerscope.Complete()完成内部作用域吗?
如果您希望从事务上下文中的故障中恢复,则需要使用事务保存点。不幸的是,托管System.Transaction
不支持保存点。不仅如此,如果使用事务作用域,您甚至不能直接使用保存点,因为事务作用域将升级为分布式事务,而保存点在分布式上下文中不起作用。
您可以使用平台特定的SqlTransaction
,它支持Save()
作为保存点。有关事务感知异常处理的示例,请参阅异常处理和嵌套事务。