In this post, I cover three cases in which transaction scope is being used to show rollback when an error occurs during an update of multiple entities:
- when you have multiple save calls to the context;
- when you have single save with multiple object; and
- transactions across multiple contexts.
Our model is a simplified version of a “Product” object and it’s definition look like this:
using System; using System.ComponentModel.DataAnnotations; namespace EFTransactionsDemo.Model { public class Product { public int Id { get; set; } [Required] public string Name { get; set; } [Required] public DateTime DateAdded { get; set; } } }
Our context definition looks like:
using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace EFTransactionsDemo.Model { public class EFTDbContext : DbContext { public DbSet<Product> Products { get; set; } public EFTDbContext() : base("EFTransactionsDemo") { // disable proxy creation this.Configuration.ProxyCreationEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Tell Code First to ignore PluralizingTableName convention // If you keep this convention then the generated tables will have pluralized names. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }
The main method (this is demo code; in production environments, please make sure to use proper programming paradigms, do error handling, parameter checks, etc.), calls three functions that demonstrate the use of transaction scope for the three scenarios I listed above.
using System; using System.Linq; using System.Transactions; using EFTransactionsDemo.Model; namespace EFTransactionsDemo { class Program { static void Main(string[] args) { // setup CreateDatabase(); // transaction demo - 1 // wrap multiple save calls within one transaction // and roll back on a bad one TestMultipleSaveCalls(); // transaction demo - 2 // wrap multiple adds and one save within one transaction // and roll back on a bad one TestMultipleAddWithOneSaveCall(); // transaction demo - 3 // multiple contexts in same transaction TestMultipleContexts(); } private static void TestMultipleSaveCalls() { // good product Product goodProduct = new Product() { Name = "My awesome book", DateAdded = DateTime.UtcNow }; // invalid product Product invalidProd = new Product() { Name = "My awesome book part 2" // note - no date added specified }; // define our transaction scope var scope = new TransactionScope( // a new transaction will always be created TransactionScopeOption.RequiresNew, // we will allow volatile data to be read during transaction new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted } ); try { // use the scope we just defined using (scope) { // create a new db context using (var ctx = new EFTDbContext()) { // add the product ctx.Products.Add(goodProduct); // save ctx.SaveChanges(); // add the invalid product ctx.Products.Add(invalidProd); // save ctx.SaveChanges(); } // everything good; complete scope.Complete(); } } catch { } // verify that we actually rolled back using (var ctx = new EFTDbContext()) { Console.WriteLine(ctx.Products.Count()); } } private static void TestMultipleAddWithOneSaveCall() { // good product Product goodProduct = new Product() { Name = "My awesome book", DateAdded = DateTime.UtcNow }; // invalid product Product invalidProd = new Product() { Name = "My awesome book part 2" // note - no date added specified }; // define our transaction scope var scope = new TransactionScope( // a new transaction will always be created TransactionScopeOption.RequiresNew, // we will allow volatile data to be read during transaction new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted } ); try { // use the scope we just defined using (scope) { // create a new db context using (var ctx = new EFTDbContext()) { // add the product ctx.Products.Add(goodProduct); // add the invalid product ctx.Products.Add(invalidProd); // save ctx.SaveChanges(); } // everything good; complete scope.Complete(); } } catch { } // verify that we actually rolled back using (var ctx = new EFTDbContext()) { Console.WriteLine(ctx.Products.Count()); } } private static void TestMultipleContexts() { // good product Product goodProduct = new Product() { Name = "My awesome book", DateAdded = DateTime.UtcNow }; // invalid product Product invalidProd = new Product() { Name = "My awesome book part 2" // note - no date added specified }; // define our transaction scope var scope = new TransactionScope( // a new transaction will always be created TransactionScopeOption.RequiresNew, // we will allow volatile data to be read during transaction new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted } ); try { // use the scope we just defined using (scope) { // create a new db context var firstCtx = new EFTDbContext(); // create a second context var secondCtx = new EFTDbContext(); // add the product to first context firstCtx.Products.Add(goodProduct); // save firstCtx.SaveChanges(); // add the invalid product to second context secondCtx.Products.Add(invalidProd); // save secondCtx.SaveChanges(); // everything good; complete scope.Complete(); } } catch { } // verify that we actually rolled back using (var ctx = new EFTDbContext()) { Console.WriteLine(ctx.Products.Count()); } } private static void CreateDatabase() { using (var ctx = new EFTDbContext()) { ctx.Database.CreateIfNotExists(); } } } }
As always, please do leave your thoughts and comments. It is the user feedback that drives the product and blog better.
Thanks, intuitive and clear examples!
ReplyDeleteThe "TestMultipleContexts" approach fails for me every time. I keep getting "System.Transactions.TransactionManagerCommunicationException: Network access for Distributed Transaction Manager (MSDTC) has been disabled." errors. Do you have any thoughts on this process? If so, I'd be interested in hearing them. Cheers, Landon (campbelllandon@hotmail.com)
ReplyDeletefor multiple context (if they are from different databases) then they requires MSDTC to be enabled on the DB Server.
DeleteThanks & Good work. I was a example with multiple context in single TransactionScope but unable to find . This give me a better understanding.
ReplyDeleteNow i have a question, Do i need to call BeginTransaction method of DbContext or TransactionScope will take care that internally?
U can send me email on harshmah@gmail.com.
Thanks Again.
Is there a way to start transaction scope in one function and call another function that has its own transaction scope? For example...
ReplyDeleteMethod1{
New Scope1{
do something...
}
}
Method2{
new Scope1{
Call Method1()
do something...
}
}
Thanks,
AJ
i think MSDTC need to start
ReplyDeleteHi Nikhil,
ReplyDeleteCan we call multiple save on same context object, I do not require rollback.
Yes, as long as you are tracking the changes using the same context object (for example in a desktop app)
Deletehi,
ReplyDeleteFor test no. 3 (TestMultipleContexts();), i randomly hit the error "System.Data.SqlClient.SqlException (0x80131904): Transaction context in use by another session.". Any idea?
Nice one!!!!
ReplyDeleteAnil Singh
http://www.code-sample.com/
Thanks
ReplyDeleteVery interesting and good Explanation
ReplyDeleteASP NET Training
ASP NET Training
ASP NET Online Training
C-Sharp Training
Dot Net Training in Chennai
Online .Net Training
Online Entity Framework
Training
Entity Framework Training
Online Entity Framework Training from India
Entity Framework Training in Chennai
thanks
ReplyDeleteThe blog or and best that is extremely useful to keep I can share the ideas
ReplyDeleteof the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
tanki online | 2048 game |
tanki online game
This comment has been removed by the author.
ReplyDeleteThe purpose of this communication is to advance a few of the techniques available in structuring small business sale transactions and to emphasize the value an experienced team brings in structuring the transaction.소액결제현금화
ReplyDeleteSuccessful e-commerce websites have one thing in common. They not only have a secure online transaction system in place but they display proof of the security measures in place to assure the customer at every stage of the transaction.소액결제현금화
ReplyDelete
ReplyDeletevery good artkel.
Cara Menggugurkan Kandungan
Dokter Spesialis Kandungan
Penyebab Telat Haid
메이저놀이터
ReplyDeleteGOOD GOOD COIERE
온라인카지노
ReplyDeletegood godc coiwoeir ee
먹튀폴리스
ReplyDeletewow goodkj coiewere
먹튀검증
ReplyDeleteyou for your efforts, bringing you interesting information. Thank you
사설토토
ReplyDeleteur efforts, bringing you interesting information. Thank you
안전놀이터
ReplyDeleteefforts, bringing you interesting information. Thank y
메이저놀이터
ReplyDeletecierkj coi owere
토토
ReplyDeleteck ejroicoiwere
슬롯게임
ReplyDeleteckejr coiweore
Đại lý vé máy bay Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu tiền
giá vé máy bay từ mỹ về việt nam tháng 12
khi nào có chuyến bay từ anh về việt nam
máy bay từ pháp về việt nam
whoah this blog is excellent i like studying
ReplyDeleteyour posts. Stay up the good work! You recognize, a lot of people are hunting around for
this info, you could help them greatly.
Also visit my page :::: 부산오피
(jk)
Aivivu - đại lý chuyên vé máy bay trong nước và quốc tế
ReplyDeletevé máy bay đi Mỹ hạng thương gia
vé về việt nam từ mỹ
giá vé máy bay từ Vancouver về việt nam
thời gian bay từ nhật về vn
khi nào mở lại đường bay hàn quốc
Vé máy bay từ Đài Loan về VN
danh sách khách sạn cách ly
Melodyne Studio 5 Crack allows you to work with audio in a completely new way. One that is musical, spiritual, crystalline, and almost magical.
ReplyDeleteSlate Digital VMR Crack-mac
Serum VST Crack
Adobe XD Crack
Fl Studio Mac Crack has a selection of tools to aid in grading manipulation and editing. The digital audio platform cannot match the versatility of FL Studio’s playlist.
ReplyDeleteWinsnap Crack License Key
Microsoft Office 2019 Crack
Corel Draw X7 Crack
Such a Nice post.#Thanks For winsnap-crack You can also visit my Website activecrack.com
ReplyDeleteHi buddies, it is great written piece entirely defined, continue the good work constantly.
ReplyDeletetop UI design companies
شركة تنظيف منازل بالجبيل
ReplyDelete