Mar 29 2016

How to Maintain Consistency in SQL Tables using Linq

In .NET Framework, Transactionscope is an important class. Transaction is used under a set of short and quick tasks. If any of these tasks fails, the whole transaction should fail and all those tasks already done should rollback. Actually, in code, Transactionscope makes it transactional. For using Transactionscope, we can use the namespace, System.Transactions.TransactionScope.

Transaction is a unit of work. The usage of transaction is to ensure consistency and integrity of the database. If all the tasks succeed, then the transaction will be successful, and therefore all the data modifications performed during the transactions are successfully committed. If any error occurs, then rollback the transaction to undo the data modifications that occurred in the transaction.


Suppose a customer needs to transfer money from bank account-X to bank account-Y.
There are two tasks.
1.Withdraw amount from account-X
2.Deposit that amount to account-Y

Here there are two processes. One is cash withdrawal and the other is cash deposit. Transferring cash will only be accurate and successful if both the processes are individually successful. If any of the processes fails, ie, the first process succeeds and the second process fails, then cash would get deducted from customer account-X but not get deposited in account-Y. So there the calculations fail. Here we can use the transactionscope.
The steps are given below:
1.Add reference System.Transactions to the project.
2.Create a transactional scope.
3.Write code which needs to have transactional support.
4.Execute the TransactionScope.Complete method to commit and finish a transaction.


Now if an exception occurs, ie, any task – task 1(), task 2() or task 3() – fails, then it will catch the exception in the catch block and all the operations will be rolled back automatically.

If no issues occur, ie, all the tasks succeed, then the transaction in which the scope participates is allowed to proceed. If the exception forms in the scope, then the transaction in which the transactionscope participates will be rolled back.

Transaction Rolling back

If we need to rollback the transaction, then we should not call the complete method within the transactionscope. For example, if the exception occurs, then throw an exception within the scope. The transaction in which it participates should be rolled back. When all the tasks get completed successfully in the transactionscope, then call the complete method to inform the transaction to commit. If any failure occurs, then the transaction is aborted.


Transactionscope makes the code transactional. If one or more tasks succeed, and one fails, then all tasks will roll back. In transactionscope, there is a block of code. If the code is executed successfully, the transaction commits . Otherwise the task will roll back.

Loading Disqus Comments ...