如何回滚实体框架中的事务 [英] How to rollback a transaction in Entity Framework

查看:133
本文介绍了如何回滚实体框架中的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的String [] = usersToAdd新的字符串[] {ASD,asdert,gasdff6};
使用(实体上下文=新的实体())
{
    的foreach(在usersToAdd字符串用户)
    {
        context.AddToUsers(新用户{名称=用户});
    }
    尝试
    {
        context.SaveChanges(); //抛出异常:用户gasdff6'已经存在。
    }
    赶上(例外五)
    {
        //回滚所有的变化,包括两个previous用户。
    }

或者,也许这是自动完成的,这意味着如果发生错误,提交更改的所有更改取消。
是什么呢?


解决方案

确定

我创建了一个样本像是从这个问题,我后记在数据库中检查,没有添加用户。该示例应用程序一个

结论:ObjectContext.SaveChange,将自动交易

注意:我相信,如果执行存储过程将需要交易等

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.

Conclusion: ObjectContext.SaveChange it's automatically a transaction.

Note: I believe transactions will be needed if executing sprocs etc.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆