How to rollback a transaction in Entity Framework

社会主义新天地 提交于 2019-12-17 16:28:32

问题


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?


回答1:


OK

I created a sample a application like the example from the 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.




回答2:


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

}


来源:https://stackoverflow.com/questions/1070040/how-to-rollback-a-transaction-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!