Monday, September 2, 2019

Lebih Baik TransactionScope dari pada Begin Transaction()


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 :

  1. using (var txscope =new TransactionScope(TransactionScopeOption.RequiresNew))    
  2. {    
  3.    try    
  4.    {    
  5.       using (SqlConnection objConn = new SqlConnection(strConnString))    
  6.       {    
  7.             objConn.Open();    
  8.             SqlCommand objCmd1 = new SqlCommand("insert into tblProject values(1, 'TestProject')", objConn);    
  9.             SqlCommand objCmd2 = new SqlCommand("insert into tblProjectMember(MemberID, ProjectID) values(2, 1)", objConn);    
  10.   
  11.             objCmd1.ExecuteNonQuery();    
  12.             objCmd2.ExecuteNonQuery(); // Throws exception due to foreign key constraint  
  13.   
  14.             //The Transaction will be completed    
  15.             txscope.Complete();               
  16.       }         
  17.    }    
  18.    catch(Exception ex)    
  19.    {    
  20.       // Log error    
  21.       txscope.Dispose();    
  22.    }    
  23. }  

Artikel Terkait


EmoticonEmoticon