Wednesday, December 26, 2012

Type of Transactions in .NET

There are two main types of transactions connection transactions and ambient transactions.

Connection transactions
These type of transactions are bind to the database connection (SqlTransaction). Which means you need an active database connection to use the transaction. Connection transaction doesn't allow "create/use/release" usage, and doesn't allow cross-db work.

using (SqlTransaction tran = conn.BeginTransaction())

       // your code

If you need to call any method in the scope you need to pass the connection as a parameter and keep the same transaction running.

To overcome the above mentioned issues TransactionScope class is introduced since .NET 2.0. 

using(TransactionScope tran = new TransactionScope())

Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If any error occurred in any methods the main transaction is rolled back. Transaction scope is not bind to the database connection. 

No comments:
Write comments
Recommended Posts × +