简体   繁体   English

如何在Entity Framework中回滚事务

[英]How to rollback a transaction in Entity Framework

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? 是吗?

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. 结论:ObjectContext.SaveChange它自动成为一个事务。

Note: I believe transactions will be needed if executing sprocs etc. 注意:我相信如果执行sprocs等将需要事务。

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. 我相信(但我不是EF的专家),在调用context.SaveChanges之前,事务没有开始。 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. 替代方案(如果你想控制交易)[来自J.Lerman的“编程实体框架” O'Reilly,pg。 618] 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();
    }
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM