[转]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 !!

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.

时间: 2024-11-10 08:20:48

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

[LintCode] Read Characters From File - Multiple Calls

The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. By using the read4 API, implement the function

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

[抄题]: 接口:int read4(char * buf)一次从文件中读取 4 个字符.返回值是实际读取的字符数. 例如,如果文件中只剩下 3 个字符,则返回 3.通过使用read4 接口,实现从文件读取 n 个字符的函数int read(char * buf,int n). [暴力解法]: 时间分析: 空间分析: [思维问题]: [一句话思路]: [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入): [画图]: 用数组实现队列的原理是:进入时是ta

Oracle Applications Multiple Organizations Access Control for Custom Code

文档 ID 420787.1 White Paper Oracle Applications Multiple Organizations Access Control for Custom Code Checked for relevance on 12-JAN-2011 See Change Record This document discusses how to update the customization code that is affected by the access co

MYSQL术语表

MYSQL术语表 http://dev.mysql.com/doc/refman/5.6/en/glossary.html MySQL Glossary These terms are commonly used in information about the MySQL database server. This glossary originated as a reference for terminology about the InnoDB storage engine, and th

postgresql大批量数据导入方法

一直没有好好关注这个功能,昨天看了一下,数据库插入有瓶颈,今天研究了一下: 主要有以下方案: 1.使用copy从文件导入: copy table_001(a, b, "f", d, c, "e") from 'd:/data1.txt' (delimiter ','); 速度极快: 不带索引: 查询成功: 共计 69971 行受到影响,耗时: 4351 毫秒(ms).        查询成功: 共计 69971 行受到影响,耗时: 4971 毫秒(ms).     

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 tool has a wonderful recorder feature that records a user's activities and automatically generates code that simulates these activities. You can then im

Multiple HTTPS Bindings IIS 7 Using appcmd

http://toastergremlin.com/?p=308 Sometimes when using a wildcard SSL or Unified Communications Certificate (UCC) it is necessary to add multiple https host headers for a single IP. Unfortunately the IIS 7 GUI does not allow you to set a host header o

[Selenium+Java] TestNG: Execute multiple Test Suites

Original URL: https://www.guru99.com/testng-execute-multiple-test-suites.html TestNG: Execute multiple Test Suites TestNG enables you to run test methods, test classes and test cases in parallel inside your project. By performing parallel execution,

Autotools Mythbuster

Preface Diego Elio?"Flameeyes"?Pettenò Author and Publisher?<[email protected]> SRC=https://autotools.io/index.html David J.?"user99"?Cozatt Miscellaneous Editing?<[email protected]> Copyright ? 2009-2013 Diego Elio Pettenò