[转]Wrapping multiple calls to SaveChanges() in a single transaction
本文转自: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 !!
[转]Wrapping multiple calls to SaveChanges() in a single transaction的更多相关文章
- 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 ...
- 从文件中读取字符-多次调用read characters from file multiple calls
[抄题]: 接口:int read4(char * buf)一次从文件中读取 4 个字符.返回值是实际读取的字符数. 例如,如果文件中只剩下 3 个字符,则返回 3.通过使用read4 接口,实现从文 ...
- Oracle Applications Multiple Organizations Access Control for Custom Code
档 ID 420787.1 White Paper Oracle Applications Multiple Organizations Access Control for Custom Code ...
- Entity Framework中DbContext结合TransactionScope提交事务的正确方式
问: I would like know what is the best possible way to implement transactions with DBContext. In part ...
- postgresql大批量数据导入方法
一直没有好好关注这个功能,昨天看了一下,数据库插入有瓶颈,今天研究了一下: 主要有以下方案: 1.使用copy从文件导入: copy table_001(a, b, "f", d, ...
- XA Transactions Restrictions on XA Transactions
小结: 1.innodb支持XA事务: 2.XA协议作为资源管理器(数据库)与事务管理器的接口标准: 3.提交或者回滚的点:必须所有的组件被提交或者被回滚: 4.2阶段 PC-1,TM告知所有RM要准 ...
- 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 ...
- WCF Concurrency (Single, Multiple, and Reentrant) and Throttling
http://www.codeproject.com/Articles/89858/WCF-Concurrency-Single-Multiple-and-Reentrant-and Introduc ...
- 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 ...
随机推荐
- day08.1-Linux软件包管理
Linux系统中的两种软件包:tar,保存内容为源码,编译后再安装:rpm,保存内容为编译后的机器码,直接安装.其中,rpm软件包由5部分构成,分别为: 第1部分是name,表示这个rpm软件包的名称 ...
- Spring Boot多数据源
我们在开发过程中可能需要用到多个数据源,我们有一个项目(MySQL)就是和别的项目(SQL Server)混合使用了.其中SQL Server是别的公司开发的,有些基本数据需要从他们平台进行调取,那么 ...
- springMVC 学习笔记(一):springMVC 入门
springMVC 学习笔记(一):spring 入门 什么是 springMVC springMVC 是 spring 框架的一个模块,springMVC 和 spring 无需通过中间整合层进行整 ...
- LOSKI,我
2019年入驻github以及博客园 在发现用github的issue写博客稍微有些奇怪后决定开辟这个更适合写博的空间 2019/4/1 目前大一,计算机专业,尚未分流 更多的时间花在了数据结构与算法 ...
- 2008R2 无法安装 HDP Apache 系列服务解决方案
执行下面的 PS 就好了. 特别是 第三行在执行的时候选择 [A] Set-ExecutionPolicy "AllSigned" Enable-PSRemoting Set- ...
- CentOS 中安装 jdk
1.检查是否安装jdk rpm -qa|grep jav [root@hadoop110 opt]# rpm -qa|grep java 2.卸载版本地域1.7 的jdk rpm -e 软件包 [r ...
- Django 中的中间件
Django 中的中间件 Django 中间件 中间件介绍 前戏 之前在判断登录的时候使用的是装饰器的功能,通过给视图函数加装饰器来增加判断是否登录的功能.但此方法的缺点是必须给每个需要判断登录的视 ...
- 【算法笔记】B1021 个位数统计
1021 个位数统计 (15 分) 给定一个 k 位整数 N=dk−110k−1+⋯+d1101+d0 (0≤di≤9, i=0,⋯,k−1, dk−1> ...
- P2048 [NOI2010]超级钢琴
传送门 考虑维护前缀和 $sum[i]$ 那么对于每一个位置 $i$ ,左端点为 $i$ 右端点在 $[i+L-1,i+R-1]$ 区间的区间最大值容易维护 维护三元组 $(o,l,r)$ ,表示左端 ...
- BZOJ - 1941 最远估价
题意:求给出的所有点的最远点减最近点的最小差值 KD树的最远估价和最近估价略微不同,直接找最远垂线,反正xjb改一下就过了 #include<bits/stdc++.h> #define ...