In Entity Framework, how do you rollback a transaction?

c# entity-framework rollback savechanges transactions

Question

string[] usersToAdd = new string[] { "asd", "asdert", "gasdff6" };
using (Entities context = new Entities())
{
    foreach (string user in usersToAdd)
    {
        context.AddToUsers(new User { Name = user });
    }
    try
    {
        context.SaveChanges(); //Exception thrown: user 'gasdff6' already exist.
    }
    catch (Exception e)
    {
        //Roll back all changes including the two previous users.
    }

Or maybe this is done automatically, in which case all modifications are undone if a mistake is made. is it?

1
9
7/1/2009 5:49:26 PM

Accepted Answer

OK

I made a sample application that was similar to the one in the question, and when I examined the database later, I saw that no new users had been added.

In conclusion, a transaction is created automatically by ObjectContext.SaveChange.

Note: I think transactions will be necessary if running sprocs, etc.

12
1/9/2013 9:31:31 AM

Popular Answer

I think so up to the call to context, however I'm not a longtime specialist on EF. When you click SaveChanges, no transaction is initiated. I would anticipate that any transaction the call began would be instantly rolled back if an exception occurred. Alternatives (in case you want to be in control of the transaction) [from page 618 of "Programming Entity Framework" by J.Lerman O'Reilly]

using (var transaction = new System.Transactions.TransactionScope())
{
  try
  {
    context.SaveChanges();
    transaction.Complete();
    context.AcceptAllChanges();
  }
  catch(OptimisticConcurrencyException e)
  {
    //Handle the exception
    context.SaveChanges();
  }
}

or

bool saved = false;
using (var transaction = new System.Transactions.TransactionScope())
{
  try
  {
    context.SaveChanges();
    saved = true;
  }
  catch(OptimisticConcurrencyException e)
  {
    //Handle the exception
    context.SaveChanges();
  }
  finally
  {
    if(saved)
    {
      transaction.Complete();
      context.AcceptAllChanges();
    }
  }

}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow