Rollback using TransactionScope in LINQ

Hi Techies

There is a very good feature to achieve 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:

using (TransactionScope ts = new TransactionScope())

{

    Customer customer = new Customer();

    db.Customer.InsertOnSubmit(customer);    // To insert into the Customer table
    db.SubmitChanges();                     // inserted into database, but transaction not yet committed  
    CustomerDetails objCustomerDetails = new CustomerDetails();  // Creating an object of CustomerDetails 
    db.CustomerDetails.InsertOnSubmit(objCustomerDetails);        // queues up insert to Customer table
    db.SubmitChanges();    // insert done in db but still not committed

    ts.Complete();    // The inserted in above statement are committed to the db
}

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

Will try to explore more in future.

Cheers .Net
Ebook Download
View all
Learn
View all