[转]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 ...
随机推荐
- virtueBox实现虚拟机的复制和粘贴
1.在设备--共享粘贴板--勾选双向. 2.在设备--拖放--勾选双向. 3.在设备--安装增强功能,然后进入虚拟机安装增强功能即可.
- 搭建jumpserver堡垒机
环境 系统: CentOS 7 IP: 192.168.244.144 关闭 selinux 和防火墙 # CentOS 7 $ setenforce 0 # 可以设置配置文件永久关闭 $ syst ...
- 【转】C#中静态方法和非静态方法的区别
源地址:https://www.cnblogs.com/amoshu/p/7477757.html 备注:静态方法不需要类的实例化就能调用,因为它是一直保存在内存中,不像非静态方法一样要放在实例化类时 ...
- 一、pytest的介绍和安装
需要针对一个项目系统开发一套UI自动化测试脚本,自己结合着学习,采用了pytest去实现,这里留下记录. 什么是pytest pytest 是一个非常成熟的全功能的Python测试框架 可以胜任uni ...
- JS 对象的三种创建方式
变量 instanceof 类型的名字----->布尔类型,true就是这种类型,false不是这种类型 在当前的对象的方法中,可以使用this关键字代表当前的对象 1.调用系统的构造函数创 ...
- CoreML的学习
在苹果官网下载模型model 链接: https://developer.apple.com/machine-learning/
- Django--队列2
celery 4.2 -Ofair现在是默认的调度策略 关于-Ofair命令行选项的作用存在很多混淆,并且在解释中使用术语“预取”可能没有帮助,因为这个术语在AMQP中有多么混乱. 当使用prefor ...
- 008 Android activity实现多个界面的相互跳转(主要利用Intent)
1.activity介绍 一个activity就把他理解成一个页面 2.新建activity流程 如图所示在com.lucky.test06的目录下,右击new--->Activity---&g ...
- LeetCode154.寻找旋转排序数组中的最小值 II
154.寻找旋转排序数组中的最小值 II 描述 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] ). ...
- CF248E Piglet's Birthday(概率dp)
题面 luogu CodeForces 题解 \(orz\) yyb 转移蜜罐其实是吓唬人的...... 转移的蜜罐都是尝试过的,所有只关心当前架子上的蜜罐数 设\(f[i][j]\)表示第i个货架有 ...