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())2:3: {4:5: Customer customer = new Customer();6:7: db.Customer.InsertOnSubmit(customer); // To insert into the Customer table8: db.SubmitChanges(); // inserted into database, but transaction not yet committed9: CustomerDetails objCustomerDetails = new CustomerDetails(); // Creating an object of CustomerDetails10: db.CustomerDetails.InsertOnSubmit(objCustomerDetails); // queues up insert to Customer table11: db.SubmitChanges(); // insert done in db but still not committed12:13: //To rollback explicitly from a transaction execute one of the following14: Transaction.Current.Rollback();15: tscope.Dispose();16:17: // To commit the complete transaction18: tscope.Complete(); // The inserted in above statement are committed to the db19: }
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.
Thanks.
Keep coding and Stay Happy
Thanks. Works like charm.. :)
ReplyDelete