如何在实体框架中回滚事务

How to rollback a transaction in 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.
    }

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

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.

这篇关于如何在实体框架中回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)