Using multiple Object Contexts in a Transaction

The scenario: You have 2 Entity Models, and you need to call operations on the ObjectContext of each of them, the operations should be atomic, in that either both operations should succeed or fail so that your databases are consistent.
This is fairly straightforward to accomplish using a TransactionScope.
ObjectServices is smart enough to detect if the ObjectContext is in a surrounding TransactionScope and if so,use that scope.
NOTE:If a scope is not specified, then ObjectContext by default creates a new scope internally when saving changes.

 
  1. using (TransactionScope scope = new TransactionScope())  
  2.            {  
  3.                using (RequestDBContext context = new RequestDBContext())  
  4.                {  
  5.                    RequestType rt = new RequestType  
  6.                    {  
  7.                         Name="Test-2",                            
  8.                    };  
  9.                    context.AddToRequestTypeSet(rt);  
  10.                    context.SaveChanges();  
  11.                }  
  12.   
  13.                using (RequestDBContext context = new RequestDBContext())  
  14.                {  
  15.                      
  16.                    Status stat = context.StatusSet.First(s => s.Name == "Pending Approval");  
  17.                    context.DeleteObject(stat);  
  18.                    context.SaveChanges();  
  19.                }  
  20.                scope.Complete();  
  21.            }  

In the above code I'm using the same EDM for both ObjectContexts, but I could very well use different EDMs.
If we reach the end of the 2nd using statement, then we can complete the transaction and persist all our changes.
If an exception is thrown then nothing is changed in the database and the transaction aborts.
Hope this helps.


UPDATE:5/16/09
Using TransactionScope requires MSDTC, the following links have good information to help setup/troubleshoot MSDTC for various environments
How to Enable MSDTC on a Web Server
New functionality in the Distributed Transaction Coordinator service in Windows Server 2003 Service Pack 1 and in Windows XP Service Pack 2
Thursday, February 19, 2009 5:08 PM mmazur How to configure and troubleshoot MSDTC

kick it on DotNetKicks.com

Print | posted @ Wednesday, May 13, 2009 11:58 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: