TransactionScope
What is TransactionScope ?
- A transaction scope defines a block of code that participates in a transaction.
- If the code block completes successfully, the transaction manager commits the transaction. Otherwise, the transaction manager rolls back the transaction.
- If multiple data sources are accessed in same context, then ENLISTED transactions are promoted to DTC.
Usage Notes
- Define Scope
- Connect one data source
- Connect another data source
- Manipulate data
- On success, Set complete flag to true
- Close the scope
Implementation
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
string strCmd = "SQL to Execute";
conn = new SqlClient.SqlConnection("Connection to DB1");
conn.Open()
objCmd = new SqlClient.SqlCommand(strCmd, conn);
objCmd.ExecuteNonQuery();
string strCmd2 = "SQL to Execute";
conn2 = new SqlClient.SqlConnection("Connection to DB2");
conn2.Open()
objCmd2 = new SqlClient.SqlCommand(strCmd2, conn2);
objCmd2.ExecuteNonQuery();
}
TransactionScope Options
What is TransactionScope Option?
- Define behavior and scope of transaction scope.
- Defines behavior of ambient transaction.
- Start, Re-Use or ignore current transaction context.
Usage Notes
- Required - Transaction MUST present and re-use if already exists.
- RequiresNew - Transaction MUST present and always create a new transaction.
- Suppres- Transaction should not be used, even if exists.
Implementation
using(TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TransOptions))
using(TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TransOptions))
using(TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, TransOptions))
No comments:
Post a Comment