views:

1459

answers:

2
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, meaning that if error occurs, committing changes are canceled for all the changes. is it?

+3  A: 

I believe (but I am no long time expert in EF) that until the call to context.SaveChanges goes through, the transaction is not started. I'd expect an Exception from that call would automatically rollback any transaction it started. Alternatives (in case you want to be in control of the transaction) [from J.Lerman's "Programming Entity Framework" O'Reilly, pg. 618]

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();
    }
  }

}
FOR
"I believe" that what?
Shimmy
In essence, I believe you get transaction rollback for free in the simple scenario, and that you will need to handle transactions as demonstrated in the two examples for more complex scenarios. Your sample app seems to confirm this.Sorry if my wording was less than stellar - was in-between meetings when I wrote this yesterday.
FOR
+3  A: 

OK

I created a sample a pplication like the rxample above (in the question) and afterwords I checked in the DB and no users were added.

Conclusion: ObjectContext.SaveChange it's automatically a transaction.

Note: I believe transactions will be needed if executing sprocs etc.

Shimmy