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!
ReplyDeleteGreat Article
DeleteIEEE Final Year Projects for CSE
IEEE Project Centers in Chennai
The "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 blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck
ReplyDeletehttp://www.jualobataborsiherbal.com/ obat aborsi
http://caramenggugurkankandungan.info/ cara menggugurkan kandungan
http://www.jualobataborsiherbal.com/cara-menggugurkan-kandungan/ cara menggugurkan kandungan
http://obataborsi59.com/ obat aborsi
http://obataborsi59.com/cara-menggugurkan-kandungan-dengan-cepat-dan-aman/ cara menggugurkan kandungan
http://obattelatdatangbulan.info/ obat telat datang bulan
http://klinikobataborsi.com/ jual obat aborsi
http://jualobatpenggugurkandungan.net/ obat penggugur kandungan
http://tandatandakehamilan.net/ tanda tanda kehamilan
http://tandatandakehamilan.net/cara-cepat-dan-selamat-menggugurkan-kandungan/ cara menggugurkan kandungan
This comment has been removed by the author.
ReplyDeletenow present in your city cara menggugurkan kandungan
ReplyDelete1. manfaat kurma untuk persalinan
2. manfaat buah nanas
3. aktivitas penyebab keguguran
4. apakah usg berbahaya
5. penyebab telat haid
6. cara melancarkan haid
7. cara mengatasi keputihan
8. tanda tanda menopause
The 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
The information you shared is wonderful to me, thank you and have a nice day. You can also search for information at Magical World EZ,
ReplyDeleteyorg 3 ,
Sketchful.io full screen,
bois.io 3d battle royale ,
bombom io ,
I’m much pleased with your good work. you have good knowledge for article writing and this article is amazing. I am waiting for your next article…. Thank you so much
ReplyDeleteFree Games Online For Girls
Kids Free Games Online
Online Free Games
Free Games For
Top Free Games
Free Games Online
Best Free Games Online
All Free Games Online
Free Games For Kids Online
Best Free Games 2020
I thank you for your efforts, bringing you interesting information. Thank you so much
ReplyDeletefree games online pool
cool math games
cool games for kids
Cool Cool Cool games
Cool Games to Play Online
Cool Games for Kids Free
Poki Games Online
Free Games PC
Pogo Games Online
Pogo Free Game
메이저놀이터
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
That's a really good piece of writing. It's been a lot of help. I'll help you.토토사이트
ReplyDeleteno deposit bonus forex 2021 - takipçi satın al - takipçi satın al - takipçi satın al - tiktok takipçi satın al - instagram beğeni satın al - instagram beğeni satın al - google haritalara yer ekleme - btcturk - tiktok izlenme satın al - sms onay - izlenme-satin-al.com/youtube - google haritalara yer ekleme - no deposit bonus forex 2021 - tiktok jeton hilesi - tiktok beğeni satın al - binance - takipçi satın al - uc satın al - finanspedia.com - sms onay - sms onay - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - perde modelleri - instagram takipçi satın al - instagram takipçi satın al - cami avizesi - marsbahis
ReplyDeletewhoah 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
Hey there! I could have sworn I’ve been to this website before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely happy I found it and I’ll be book-marking and checking back frequently ty le keo
ReplyDeleteMelodyne 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
ReplyDeleteIt's too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site 꽁머니 and leave a message!!
ReplyDeleteYou Can Also Download Free Software & Mac
ReplyDeletehttps://tijacrack.com/serum-vst-crack/
Hi buddies, it is great written piece entirely defined, continue the good work constantly.
ReplyDeletetop UI design companies
I was looking for this certain information for a very long time.
ReplyDeleteThank you and best of luck.
M3 Data Recovery Crack is a program for recovering data. Recovering crude information is one of the primary ways to recover data from a store. A framework that is compatible with this type of equipment or unit can be connected remotely.
M3 Data Recovery Crack can be accomplished. Data from a store is recovered principally when crude data is being recovered. The framework can be remotely connected to external equipment or units of this type.
M3 Data Recovery Crack is used to recover data. Data can be recovered from a stored medium by obtaining crude information. Connecting this type of equipment can be accomplished remotely using a framework that is compatible with it.
ReplyDeleteGreat info!
I recently came across your blog and have been reading along.
M3 Data Recovery Crack is capable of recovering data. Recovery of data can be done using the crude information extracted from the storage medium. This type of equipment can be remotely connected using a framework compatible with it.
M3 Data Recovery Crack used to repair and recover data from damaged hard drives. A data recovery tool that recovers deleted files and partitions from corrupted hard drives
Camtasia Studio Crack is a powerful software for creating video tutorials and presentations. The best all-in-one screen recorder and video editor. It provides an easy way to record and create professional-looking videos.
شركة تنظيف منازل بالجبيل
ReplyDelete