Geeks With Blogs
Sudheer Kumar ASP.Net, C#, BizTalk, MSBuild, WPF, WCF, WF....

 

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!

Posted on Sunday, April 11, 2010 9:57 AM | Back to top


Comments on this post: Entity Framework & Transactions

# re: Entity Framework & Transactions
Requesting Gravatar...
it would be nice if you mentioned that the TransactionScope object was the one from the System.Transactions assembly
Left by frank on Oct 27, 2011 10:09 PM

# re: Entity Framework & Transactions
Requesting Gravatar...
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
Left by zeshan ajmal on Apr 24, 2012 1:34 PM

# re: Entity Framework & Transactions
Requesting Gravatar...
the TransactionScope object was the one from the System ??
Left by silicone watch on Aug 19, 2012 7:59 PM

Your comment:
 (will show your gravatar)


Copyright © Sudheer Kumar | Powered by: GeeksWithBlogs.net