2009-07-01 96 views
9
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. 
    } 

或者也许这是自动完成的,这意味着如果发生错误,所有更改的提交更改将被取消。 是吗?如何在实体框架中回滚事务

回答

12

我创建加入像从问题和后记我在DB检查,没有用户的示例的应用程序的样品。

结论:ObjectContext.SaveChange它自动成为一个事务。

注:我相信,如果执行存储过程等

8

我相信(但我没有很长时间的EF专家),直到调用context.SaveChanges通过,交易没有开始。我期望来自该调用的异常会自动回滚它开始的任何事务。 替代品(如果你想控制交易)[来自J.Lerman's "Programming Entity Framework" O'Reilly, 618]

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

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

} 
+0

“我相信”,将需要交易是什么? – Shimmy 2009-07-01 17:37:59

+0

从本质上讲,我相信在简单场景中您可以免费获得事务回滚,并且您将需要处理事务,如更复杂场景的两个示例中所示。你的示例应用似乎证实了这一点。 对不起,如果我的措辞比恒星 - 是在我昨天写这个会议之间的会议之间。 – FOR 2009-07-02 11:38:16