What is the difference between TransactionScope and BeginTranaction()??
- TransactionScope is usually a better choice because it allows you to nest calls to other methods that might require a transaction without you having to pass the transaction state around.
- With TransactionScope, as long as the scope exists, it will handle everything that registers with the current Transaction on the thread, making your code cleaner, and more maintainable.
- TransactionScope uses MS DTC(Microsoft Distributed Transaction Coordinator) for transaction management.
- Due to its ease of use and efficiency, it is recommended that you use the TransactionScope class when developing a transaction application.
Sample :
- using (var txscope =new TransactionScope(TransactionScopeOption.RequiresNew))
- {
- try
- {
- using (SqlConnection objConn = new SqlConnection(strConnString))
- {
- objConn.Open();
- SqlCommand objCmd1 = new SqlCommand("insert into tblProject values(1, 'TestProject')", objConn);
- SqlCommand objCmd2 = new SqlCommand("insert into tblProjectMember(MemberID, ProjectID) values(2, 1)", objConn);
- objCmd1.ExecuteNonQuery();
- objCmd2.ExecuteNonQuery(); // Throws exception due to foreign key constraint
- //The Transaction will be completed
- txscope.Complete();
- }
- }
- catch(Exception ex)
- {
- // Log error
- txscope.Dispose();
- }
- }
EmoticonEmoticon