Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TransactionScope and database connections

Do TransactionScope work with closed database connections?

using (var transaction = new TransactionScope(TransactionScopeOption.Required))
{
    // creates a new connection, does stuff, commit trans and close
    repos1.DoSomething(); 

    // creates a new connection, does stuff, commit trans and close
    repos2.DoSomething(); 

    transaction.Complete();
}
like image 820
jgauffin Avatar asked Feb 14 '11 20:02

jgauffin


2 Answers

Yes, that should work fine. Internally, the connections should be kept open until the transaction completes. Keep in mind that DTC may be required if multiple connections are used though, even if they are to the same database.

Also, you don't mention which database you are using, but there were bugs in the MySQL implementation that caused this not to work. For MySQL, this was fixed in MySQL 5.1.3.

like image 150
Eric Petroelje Avatar answered Oct 24 '22 18:10

Eric Petroelje


http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

Transactions started through System.Transactions are controlled through the System.Transactions infrastructure, and are not affected by SqlConnection.Close.

Calling Close just means that your code is done with the connection. If the ADO.NET infrastructure still wants the connection (to complete a transaction, or for connection pooling), the connection remains open.

like image 28
Amy B Avatar answered Oct 24 '22 17:10

Amy B