Entity Framework & Transactions

Posted by Sudheer Kumar on Geeks with Blogs See other posts from Geeks with Blogs or by Sudheer Kumar
Published on Sun, 11 Apr 2010 14:57:50 GMT Indexed on 2010/04/11 15:13 UTC
Read the original article Hit count: 568

Filed under:

 

There are many instances we might have to use transactions to maintain data consistency.

With Entity Framework, it is a little different conceptually.

Case 1 – Transaction b/w multiple SaveChanges():

here if you just use a transaction scope, then Entity Framework (EF) will use distributed transactions instead of local transactions. The reason is that, EF closes and opens the connection when ever required only, which means, it used 2 different connections for different SaveChanges() calls.

To resolve this, use the following method. Here we are opening a connection explicitly so as not to span across multipel connections.

 

using (TransactionScope ts = new TransactionScope())
{
    context.Connection.Open();

    //Operation1 : context.SaveChanges();

    //Operation2 :  context.SaveChanges()

    //At the end close the connection

    ts.Complete();

}

catch (Exception ex)

{

      //Handle Exception

}

finally
{
      if (context.Connection.State == ConnectionState.Open)
      {
           context.Connection.Close();
      }
}

 

Case 2 – Transaction between DB & Non-DB operations:

For example, assume that you have a table that keeps track of Emails to be sent.

Here you want to update certain details like DataSent once if the mail was successfully sent by the e-mail client.

Email eml = GetEmailToSend();

eml.DateSent = DateTime.Now;

using (TransactionScope ts = new TransactionScope())
{

   //Update DB

   context.saveChanges();

  //if update is successful, send the email using smtp client

  smtpClient.Send();

  //if send was successful, then commit

  ts.Complete();

}

 

Here since you are dealing with a single context.SaveChanges(), you just need to use the TransactionScope, just before saving the context only.

 

Hope this was helpful!

© Geeks with Blogs or respective owner