我正在尝试测试第一个事务,如果它是成功的,那么我尝试第二个事务,如果第二个事务也是一个成功,那么我将两个都提交,如果第二个事务失败,我需要回滚第一个事务。
所以我有以下函数,它返回一个可以是状态之一的字典:
0(表示事务失败但设法回滚)-> sql 事务
1(表示事务成功)-> sql事务
-1(表示事务失败并且没有设法回滚)-> sql 事务
Public Function execDBTrans_valMod(transactionName As String, ByVal emailSubject As String, ByVal emailBody As String, ByVal queryString As String, Optional ByVal connectionString As String = "SQLConnectionHere") As Dictionary(Of Integer, SqlTransaction)
Dim trans_dict As New Dictionary(Of Integer, SqlTransaction)
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings(connectionString).ToString) 'LATEST EXEC
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim transaction As SqlTransaction = connection.BeginTransaction(transactionName)
command.Transaction = transaction
Try
command.CommandTimeout = 3600 'Used for large updates
command.ExecuteNonQuery()
'transaction.Commit() DO NOT COMMIT so that we can commit only after we verify that pbSite can be inserted
trans_dict.Add(1, transaction)
Return trans_dict
Catch dbTrans_ex As Exception
Try
transaction.Rollback()
trans_dict.Add(0, transaction)
Return trans_dict
Catch dbTrans2_ex As Exception
trans_dict.Add(-1, transaction)
Return trans_dict
' This catch block will handle any errors that may have occurred on the server that would cause the rollback to fail, such as a closed connection.
End Try
End Try
End Using
End Function
然后我在函数中有以下代码:
Dim transPB_dict = execDBTrans_valMod("transPB", failSubject, failBody, buildInsert)
If transPB_dict.ContainsKey(1) Then 'SUCCESS
Dim transPBsite_dict = execDBTrans_valMod("transPBsite", failSubject, failBody, buildInsert_PBsite)
If transPBsite_dict.ContainsKey(1) Then
transPB_dict.Item(1).Commit()
transPBsite_dict.Item(1).Commit()
Return True
Else 'Failed to create the tables for this user so rollback all the tables that were created in the previous transaction (all the old tables in panelbase)
transPB_dict.Item(1).Rollback() 'THIS THROWS THE ERROR This SqlTransaction has completed; it is no longer usable
Return False
End If
Else
Return False
End if
我还没有提交第一个事务,为什么当我尝试回滚时它说 sqlTransaction 已完成...?
感谢您的任何帮助!