如何在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. } 

或者这可能是自动完成的,这意味着如果发生错误,则会针对所有更改取消提交更改。 是吗?

我创建了一个示例应用程序,例如问题中的示例,然后我在数据库中检查并且没有添加任何用户。

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

注意:我相信如果执行sprocs等将需要事务。

我相信(但我不是EF的专家),在调用context.SaveChanges之前,事务没有启动。 我希望该调用的exception会自动回滚它启动的任何事务。 替代方案(如果你想控制交易)[来自J.Lerman的“编程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(); } } 

要么

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