Any data-driven application needs Transaction and to ensure that the unit of work is either together successful or fail. Transaction plays a very important role. Assume that we are working with SQL Server. Now SQL Server has it’s own Transaction mechanism which could be used in Stored Procedures. However, not every time a Transaction is just about adding or deleting values to multiple database tables. It could also get involved into writing to a local system file or registry along with database manipulation. So challenge comes when you have both of them together and want to ensure if a registry access is denied then database commit has to be rolled back. At times you need to add value to database first to get the Identity field value and then right to registry. So if you do not save value to a database the you won’t get the identity field value. But the challenge is how to revert that committed change from data.
Windows Distributed Transaction Coordinator (DTC) comes very handy in those cases. However DTC is quite expensive and needs to be up and running on both database and application machines.
ADO.NET EF uses Transaction by default. For SQL Server it uses SqlTransaction. So need to bother about it if you are working on single table and referential integrity issues are occurring.
To use TransactionScope class you need to keep two things in mind
Now below code saves one entry to one database and then reads the newly generated EmpId and saves to another database
Now if you observe the Sql Profile you will find few interesting information
SQLTransaction gets promoted to DTC and then DTC takes the charge.
<p>The TransactionScope does not always involve the DTC. The TransactionScope includes transaction manager components to handle lightweight transactions without talking to the DTC. <br>See: <a href="petermeinl.wordpress.com/.../">Avoid unwanted Escalation to Distributed Transactions</a></p>
<p><br>The Entity Framework implements “Requires Transaction” for SaveChanges: it automatically creates a new Read Committed transaction around SaveChanges() if not executing in the scope of a transaction.<br> See: <a href="msdn.microsoft.com/.../bb336792.aspx">ObjectContext.SaveChanges Method</a> <br></p>
You are correct Peter. I sould have written it like "TransactionScope" increases the possibility of invoking DTC. Thanks for your valuable feedback.