本文转自:http://www.binaryintellect.net/articles/165bb877-27ee-4efa-9fa3-40cd0cf69e49.aspx

When you make any additions, modifications and deletions to an Entity  Framework DbSet and call SaveChanges(), EF starts a new transaction and executes  all the INSERT, UPDATE and DELETE operations inside that newly created  transaction. If the call to SaveChanges() succeeds the underlying transaction is  committed, otherwise the transaction is rolled back. In some cases you may want  that multiple calls to SaveChanges() be executed in the same transaction.  Luckily, Entity Framework 6 provides an easy way to accomplish the same.

Let's assume that you have an Entity Framework data model with Customer  entity as shown below:

Now suppose that you wrote the following code to add two Customer records to  the database.

NorthwindEntities db = new NorthwindEntities();

Customer obj1 = new Customer();
obj1.CustomerID = "ABCDE";
obj1.CompanyName = "Company 1";
obj1.ContactName = "Contact 1";
obj1.Country = "USA";
db.Customers.Add(obj1); db.SaveChanges();

Customer obj2 = new Customer();
obj2.CustomerID = "PQRST";
obj2.CompanyName = "Company 2";
obj2.ContactName = "Contact 2";
obj2.Country = "USA";
db.Customers.Add(obj2); db.SaveChanges();

In this case two calls to SaveChanges() are made. The first call adds the  first Customer to the database and the second call adds the other Customer to  the database. If the second call to SaveChanges() fails for some reason the  first Customer still gets added to the database because each call to SaveChanges()  runs in its own transaction.

Now let's modify this code as shown below:

using(NorthwindEntities db = new NorthwindEntities())
{
DbContextTransaction transaction = db.Database.BeginTransaction();

try
{
//insert a record
Customer obj1 = new Customer();
obj1.CustomerID = "ABCDE";
obj1.CompanyName = "Company 1";
obj1.ContactName = "Contact 1";
obj1.Country = "USA";
db.Customers.Add(obj1); //first call to SaveChanges() db.SaveChanges();

//insert another record
Customer obj2 = new Customer();
obj2.CustomerID = "PQRST";
obj2.CompanyName = "Company 2";
obj2.ContactName = "Contact 2";
obj2.Country = "USA";
db.Customers.Add(obj2); //second call to SaveChanges() db.SaveChanges();

transaction.Commit();
}
catch
{
transaction.Rollback();
}
}

Notice that the above code explicitly starts a transaction by calling  BeginTransaction() method on the Database property of the data context. The  BeginTransaction() returns a DbContextTransaction object which is stored in a  local variable. This object is used to either commit or rollback the transaction  later in the code.

The code then adds Customer entities as before and calls SaveChanges() after  each addition. This time since our code is explicitly creating a transaction,  both the calls to SaveChanges() are treated as the part of this transaction. If  both the calls to SaveChanges() are successful we call Commit() method of  DbContextTransaction object. If any of them fails we call the Rollback() method  of DbContextTransaction object.

You can test the above code by setting the CustomerID of the second Customer  to a string longer than five characters.

Note: There is also UseTransaction() method that can be used if you wish to couple EF  operations with plain ADO.NET transactions.

That's it for now! Keep coding !!

Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

[转]Wrapping multiple calls to SaveChanges() in a single transaction的更多相关文章

  1. Enlisting multiple 1-phase aware participants in the same transaction

    In some cases it may be necessary to enlist participants that aren't two-phase commit aware into a t ...

  2. 从文件中读取字符-多次调用read characters from file multiple calls

    [抄题]: 接口:int read4(char * buf)一次从文件中读取 4 个字符.返回值是实际读取的字符数. 例如,如果文件中只剩下 3 个字符,则返回 3.通过使用read4 接口,实现从文 ...

  3. Oracle Applications Multiple Organizations Access Control for Custom Code

    档 ID 420787.1 White Paper Oracle Applications Multiple Organizations Access Control for Custom Code ...

  4. Entity Framework中DbContext结合TransactionScope提交事务的正确方式

    问: I would like know what is the best possible way to implement transactions with DBContext. In part ...

  5. postgresql大批量数据导入方法

    一直没有好好关注这个功能,昨天看了一下,数据库插入有瓶颈,今天研究了一下: 主要有以下方案: 1.使用copy从文件导入: copy table_001(a, b, "f", d, ...

  6. XA Transactions Restrictions on XA Transactions

    小结: 1.innodb支持XA事务: 2.XA协议作为资源管理器(数据库)与事务管理器的接口标准: 3.提交或者回滚的点:必须所有的组件被提交或者被回滚: 4.2阶段 PC-1,TM告知所有RM要准 ...

  7. Wrapping calls to the Rational Functional Tester API——调用Rational Functional Tester封装的API

    转自:http://www.ibm.com/developerworks/lotus/library/rft-api/index.html The Rational GUI automation to ...

  8. WCF Concurrency (Single, Multiple, and Reentrant) and Throttling

    http://www.codeproject.com/Articles/89858/WCF-Concurrency-Single-Multiple-and-Reentrant-and Introduc ...

  9. Learning WCF Chapter1 Exposing Multiple Service Endpoints

    So far in this chapter,I have shown you different ways to create services,how to expose a service en ...

随机推荐

  1. Jmeter_远程启动

    Jmeter 是Java 应用,对于CPU和内存的消耗比较大,因此,当需要模拟数以千计的并发用户时,使用单台机器模拟所有的并发用户就有些力不从心,甚至会引起JAVA内存溢出错误. 其实,Jmeter的 ...

  2. HDU6336-2018ACM暑假多校联合训练4-1005-Problem E. Matrix from Arrays-前缀和

    题意是给了一种矩阵的生成方式 让你求两个左边之间的矩阵里面的数加起来的和(不是求矩阵的值) 没看标程之前硬撸写了160行 用了前缀和以后代码量缩短到原来的1/3 根据规律可以推导出这个矩阵是在不断重复 ...

  3. 决策树--Python

    决策树 实验集数据: #coding:utf8 #关键词:决策树(desision tree).特征选择.信息增益(information gain).香农熵.熵(entropy).经验熵(H(D)) ...

  4. GCD BZOJ2818 [省队互测] 数学

    题目描述 给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的数对(x,y)有多少对. 输入输出格式 输入格式: 一个整数N 输出格式: 答案 输入输出样例 输入样例#1: 复制 4 ...

  5. ssh 远程登录TX2

    TX2 端SSH操作 安装: sudo apt-get install openssh-server 确认sshserver是否启动: ps -e |grep ssh 如果看到sshd那说明ssh-s ...

  6. ionic3 IPX留海适配

    解决:使用 safe-area-inset-top 等 ios 安全区域变量 + meta 标签中设置 viewport-fit=cover https://github.com/pengkobe/r ...

  7. 如何在Qt Creator 创建一个.pri文件

    如何在Qt Creator 创建一个.pri文件 2013年10月09日 ⁄ 综合 ⁄ 共 254字 ⁄ 字号 小 中 大 ⁄ 评论关闭   这个问题很少人写,因为比较简单,但是让却让我花了好大功夫才 ...

  8. 【转】IntelliJ IDEA下自动生成Hibernate映射文件以及实体类

    1.构建项目并添加项目结构配置以及配置初始参数 1.1.如图将基本的架子搭建好     1.2.点击File,弹出的菜单中点击Project Structure:     1.3.点击左侧的Modul ...

  9. Bootstrap点击弹出注册登录

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. Jupyter 安装与应用

    用pip安装Jupyter pip install jupyter 从命令行启动笔记本服务器 jupyter notebook 前提要先启动python,这里有一个 token值,如果不是使用默认浏览 ...