C# 如何在实体框架中回滚事务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1070040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rollback a transaction in Entity Framework
提问by Shimmy Weitzhandler
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?
或者这可能是自动完成的,这意味着如果发生错误,则会取消所有更改的提交更改。是吗?
采纳答案by Shimmy Weitzhandler
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 等,将需要事务。
回答by FOR
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. 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. 618]
我相信(但我不是 EF 的长期专家)在调用 context.SaveChanges 之前,事务不会启动。我希望来自该调用的异常会自动回滚它启动的任何事务。替代方案(如果您想控制交易)[来自J.Lerman 的“编程实体框架”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();
}
}
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();
}
}
}