如何回滚在实体框架事务
-
21-08-2019 - |
题
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.
}
或者,也许这是自动完成的,这意味着如果发生错误,提交更改的所有更改取消。 是什么?
解决方案
行
我创建了一个示例像从问题和后记我在DB检查和没有添加用户。例的应用
<强>结论:ObjectContext.SaveChange,将自动交易强>
。注意:我相信,如果执行存储过程将需要交易等
其他提示
我相信,(但我在EF时间不长专家)直到调用context.SaveChanges获得通过,本次交易未启动。我希望可以调用一个异常将自动回滚它启动的任何交易。 替代品(如果你想在交易的控制)从 J.Lerman的“编程实体框架” 一> 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();
}
}
}
不隶属于 StackOverflow