Using Transactions in the Entity Framework (EF4)
You have multiple updates and want to implement transactions into your database updates in the Entity Framework? I had to do just that in C# , so I thought I’d share what I learn for to remember, and for you to learn. To do this, we must create a TransactionScope, and move around our save function a little bit in the repository. Note : The entity framework already implements transactions for single updates, so this should only be used for times when you need to either customize the transaction, or add multiple saves to a single transaction.
Step 1 : Including the Transaction Scope
You will have to add a reference to System.Transactions in your project. Then include the System.Transactions in your using statements. After that is completed, insert the following code in your save function for a basic transaction.
try { using (TransactionScope scope = new TransactionScope()) { //Code saving to the database } } catch(TransactionAbortedException) { //Code to handle the exception }
Step 2 : Setting Up Our Save to the Transaction Sope
Now that we have our basic transaction down, let’s add our database updates to the scope.
try { using (TransactionScope scope = new TransactionScope()) { //By setting the SaveOptions flag in SaveChanges to AcceptAllChangesAfterSave, we save the information for later // incase we need to log or use later. dbContext1.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); dbContext2.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); //If we get here, the transaction completed successfully scope.Complete(); } } catch(TransactionAbortedException) { //Code to handle the exception }
More Reading From the MSDN :
How to: Manage Transactions in the Entity Framework