Sudheer Kumar

ASP.Net, C#, BizTalk, MSBuild, WPF, WCF, WF....
posts - 28, comments - 111, trackbacks - 16

My Links

News



Archives

Post Categories

Entity Framework & Transactions

 

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!

Print | posted on Sunday, April 11, 2010 9:57 AM |

Feedback

Gravatar

# re: Entity Framework & Transactions

it would be nice if you mentioned that the TransactionScope object was the one from the System.Transactions assembly
10/27/2011 10:09 PM | frank
Gravatar

# re: Entity Framework & Transactions

I've tried your code and i got the following exception.

"An object with the same key already exists in ObjectStateManager. The existing object is in Modified state.
An object can only be added to the ObjectStateManager if it is in the Added State."

I'm trying to update 2 tables in a single btnclick event, tables has the relation of primary/foreign key
plz help me out
4/24/2012 1:34 PM | zeshan ajmal
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: