Thursday, January 22, 2015

Commit and Rollback using TransactionScope in LINQ

Commit and Rollback using TransactionScope in LINQ


Hi Techies

There is a very good feature to achieve commit and roll back in LINQ using TransactionScope.

For an example you are having two table  named as Customer and customerDetails.

As I've declared two tables ,Let's create a scenario , Suppose you have updated some value in current context using db.SubmitChanges() for customer table whilst other hand any exception occurs for customerDetails table then it would be weird .

Our main target is to achieve roll back transactions if something goes wrong ,rather than saving uncompleted code.

The code segment given below:

  1: using (TransactionScope tscope = new TransactionScope())
  3: {
  5:     Customer customer = new Customer();
  7:     db.Customer.InsertOnSubmit(customer);    // To insert into the Customer table
  8:     db.SubmitChanges();                     // inserted into database, but transaction not yet committed   
  9:     CustomerDetails objCustomerDetails = new CustomerDetails();  // Creating an object of CustomerDetails 
 10:     db.CustomerDetails.InsertOnSubmit(objCustomerDetails);        // queues up insert to Customer table
 11:     db.SubmitChanges();    // insert done in db but still not committed
 13:     //To rollback explicitly from a transaction execute one of the following
 14:     Transaction.Current.Rollback();
 15:     tscope.Dispose();
 17: // To commit the complete transaction
 18:     tscope.Complete();    // The inserted in above statement are committed to the db
 19: }

This is the optimum ways i found during last day .So sharing my thoughts.

To learn more about MVC please go to the following link.

MVC Articles

Keep coding and Stay Happy Smile

1 comment :