[转]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 ...
随机推荐
- The method identifyUser(Arrays.asList("group001"), String, new HashMap<>()) is undefined for the type AipFace
在使用百度云的人脸识别sdk时遇到了这个错误,网上百度不到解决的方法,当我浏览百度云的时候发现了这个 于是考虑到版本可能更新,出现了新的函数代替旧的函数,于是去查文档,文档链接如下 https://c ...
- kali linux之手动漏洞挖掘一
默认安装漏洞 phpmyadmin/setup默认安装 ubuntu/debian默认安装php5-cgi phpmyadmin/setup默认安装 使用?-d+allow_url_include%3 ...
- 【转】检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问
源地址:https://www.cnblogs.com/love522/p/4462253.html 最近在做一个网站时,有一个下载word文档功能,在本地直接调试是可以下载的,但部署到IIS上就出现 ...
- Array数组结构底层实现复习
Array数组结构底层实现复习 内容待总结: size capacity length
- ubuntu 上安装支付宝安全插件不能运行问题
1.在ubuntu的firefox浏览器中打开支付宝首页,不能登录,按照提示下载插件 aliedit.tar.gz 2.解压到某个文件夹下,有文件aliedit.sh, 运行 # sh aliedit ...
- js 冒泡事件与解决冒泡事件
事件冒泡 :当一个元素接收到事件的时候 会把他接收到的事件传给自己的父级,一直到window . html代码: <div id="div1"> <div id= ...
- ansible基本模块-cron
ansible XXX -m cron -a "name=‘XXX ’ job=‘执行的命令’ minute=XXX " ...
- 基于中间件的RBAC权限控制
RBAC 是什么 RBAC(Role-Based Access Control,基于角色的访问控制),就是用户通过角色与权限进行关联. 在 Django 中,权限就是用户对一个包含正则表达式 url ...
- CDQZ Day1
#include<cassert> #include<cstdio> #include<vector> using namespace std; ,maxt=,ma ...
- ZOJ Monthly, January 2019 I Little Sub and Isomorphism Sequences(set 妙用) ZOJ4089
写这篇博客来证明自己的愚蠢 ...Orz 飞机 题意:给定你个数组,以及一些单点修改,以及询问,每次询问需要求得,最长的字串长度,它在其他位置存在同构 题解:经过一些奇思妙想后 ,你可以发现问题是传 ...