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.
}
或者这可能是自动完成的,这意味着如果发生错误,则会针对所有更改取消提交更改。 是吗?
答案 0 :(得分:12)
行
我创建了一个示例应用程序,例如问题中的示例,然后我在数据库中检查并且没有添加任何用户。
结论:ObjectContext.SaveChange它自动成为一个事务。
注意:我认为执行sprocs等时需要进行交易。
答案 1 :(得分:8)
我相信(但我不是EF的专家),在调用context.SaveChanges之前,事务没有启动。我希望该调用的异常会自动回滚它启动的任何事务。 替代方案(如果你想控制交易)[来自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();
}
}
或
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();
}
}
}