I have an existing application that uses a lot of SqlTranaction calls. The way the application is built we get a bunch of code that looks a bit like this (error handling etc removed for brevity):
Using transaction As SqlTransaction = Database.CreateSqlTransaction()
If Not Me.FitnessSession.FitnessTestSessionID.HasValue Then
Me.FitnessSession.Insert(transaction)
Else
Me.FitnessSession.Update(transaction)
End If
SaveTestScores(transaction)
Database.CommitTransaction(transaction) 'This essentially just calls transaction.Commit()
End Using
We are in the process of ditching out hand rolled DAL and moving over to Linq to SQL, but this will be incremental as we don't have the budget to simply ditch all our legacy code. As such we will have areas where we need to use both our old code and the Linq to SQL code, all in the same transaction. I believe this can be done like this:
Using scope As New TransactionScope()
Using transaction As SqlTransaction = Database.CreateSqlTransaction()
If Not Me.FitnessSession.FitnessTestSessionID.HasValue Then
Me.FitnessSession.Insert(transaction)
Else
Me.FitnessSession.Update(transaction)
End If
SaveTestScores(transaction)
Database.CommitTransaction(transaction)
End Using
End Using
What I am unclear on is which commit to call, do I have to call scope.Complete()
or Database.CommitTransaction(transaction)
? Or is there some other option to link the two bits of code together?
Follow Up Question
Thanks @programming-hero that’s really helpful, what I am now unsure of is, when should I close sql connections? The code inside the DAL methods makes a check to see if it has been passed a transaction, if it has, then it uses the connection on that transaction and does not close the connection once it is complete, if no transaction is passed then a new connection is opened and closed for the operation. If I close a SqlConnection inside a TransactionScope does this cause a problem for the ambient transaction? I ask, because if I close a SqlConnection that has a SqlTransaction object the transaction is rolled back.