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?
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.
结论:ObjectContext.SaveChange 它自动是一个事务.
注意:如果执行 sprocs 等,我相信交易是需要的.
Note: I believe transactions will be needed if executing sprocs etc.
这篇关于如何在实体框架中回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
LINQ to SQL 和并发问题LINQ to SQL and Concurrency Issues(LINQ to SQL 和并发问题)
try/catch 块的收益回报Yield return from a try/catch block(try/catch 块的收益回报)
重用带有事务的 SqlCommand 时,我应该调用 ParameShould I call Parameters.Clear when reusing a SqlCommand with a transation?(重用带有事务的 SqlCommand 时,我应该调用 Parameters.Clear 吗
SqlTransaction 是否需要调用 Dispose?Does SqlTransaction need to have Dispose called?(SqlTransaction 是否需要调用 Dispose?)
System.Transactions.TransactionInDoubtException 的原因Reason for System.Transactions.TransactionInDoubtException(System.Transactions.TransactionInDoubtException 的原因)
如何将 TransactionScope 与 MySql 和实体框架一起使用How do I use TransactionScope with MySql and Entity Framework? (getting Multiple simultaneous connections...are not currently supported error)(如何将