Thursday, December 20, 2012

Transactions in Entity Framework with TranscationScope.


In many real time scenarios we will have to use transactions to perform Atomic operation, i.e a set so statements should get executed completely or get rollback completely. A typical example of a transactions in the Bank account example, debit X amount from account A and credit the X amount to account B, now if there is an issue between debiting from account A and crediting to account B the whole operation should be cancelled.

In this post we shall see on how to perform transactions using Entity Framework and TransactionScope. To make use of the TransactionScope we need to make sure that the MSDTC - Distributed Transaction Coordinator service is running. If the service is not running then the code will throw the following error.
The underlying provider failed on Open

In this post we will do 2 operations update the Bugs table and insert a row in the Comments table in a single transaction.

1. Open the services console Run -> services.msc and make sure that this service is running
2. Add a reference to the System.Transactions assembly to your project
3. Include this assembly in your project.
using System.Transactions;

4. Once the above are done we can go ahead and code the transaction as follows. The following method updates the Bugs table and inserts a row into the Comments table in a single transaction.


// Create a Transaction Scope Object
var transScope = new TransactionScope
                (
                    TransactionScopeOption.RequiresNew,
                     new TransactionOptions()
                     {
                         IsolationLevel = IsolationLevel.ReadUncommitted
                     }
                );
// Perform the Insert/Update within the Transcation Scope
using (transScope)
{
    // Get the Editing details
    Bugs objBug = objDBContext.Bugs.First(b => b.BugID == id);
    //
    // Update the row with the Updated Details from the View
    objBug.RaisedBy = bug.RaisedBy;
    objBug.Description = bug.Description;
    objBug.Severity = bug.Severity;
    objBug.Priority = bug.Priority;
    objBug.Status = bug.Status;
    objBug.AssignedTo = bug.AssignedTo;
    objBug.AssignedDate = bug.AssignedDate;
    //
    // Save the Changes
    objDBContext.SaveChanges();
    //
    // Add the Comment Details
    Comments objComment = new Comments();
    objComment.BugID = id;
    objComment.Comment = collection["Comments"].ToString();
    objDBContext.AddToComments(objComment);
    objDBContext.SaveChanges();
    //
    // Commit the changes
    transScope.Complete();
    //
    // Redirect to View Page.
    return RedirectToAction("Index");
} 


Search Flipkart Products:
Flipkart.com

No comments: