Friday, December 21, 2012

Transactions in Entity Framework with DbTransaction.


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 DbTransaction. Unlike the TransactionScope which needs the MSDTC - Distributed Transaction Coordinator service to be running, DbTransaction will work even if the service is not running.

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

1. Add a reference to the System.Data assembly to your project, if not added already.
2. Include this assembly in your project.
using System.Data.Common;

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

objDBContext.Connection.Open();
using (DbTransaction dbTrans = objDBContext.Connection.BeginTransaction())
{
    try
    {
        // Add the Bug Details
        objDBContext.AddToBugs(bug);
        objDBContext.SaveChanges();
        //
        // Add the Comment Details
        Comments objComment = new Comments();
        objComment.BugID = bug.BugID;
        objComment.Comment = collection["Comments"].ToString();
        objDBContext.AddToComments(objComment);
        objDBContext.SaveChanges();
        dbTrans.Commit();
        return RedirectToAction("Index");
    }
    catch (Exception ex)
    {
        dbTrans.Rollback();
        ViewData["Users"] = GetUserList();
        return View(bug);
    }
}

Search Flipkart Products:
Flipkart.com

No comments: