Tuesday 10 April 2012

Using transactions with LINQ-to-SQL

Today one of my colleague asked that how we can use transactions with the LINQ-to-SQL Classes when we use more then one entities updated at same time. It was a good question. Here is my answer for that.For ASP.NET 2.0  or higher version have a new class called TransactionScope which can be used to manage transaction with the LINQ.
Let’s take a simple scenario we are having a shopping cart application in which we are storing details or particular order placed into the database using LINQ-to-SQL. There are two tables Order and OrderDetails which will have all the information related to order. Order will store particular information about orders while OrderDetails table will have product and quantity of product for particular order.We need to insert data in both tables as same time and if any errors comes then it should rollback the transaction.
To use TransactionScope in above scenario first we have add a reference to System.Transactions like below.
TransactionScope,System.Transactions
After adding the transaction we need to drag and drop the Order and Order Details tables into Linq-To-SQL Classes it will create entities for that. Below is the code for transaction scope to use mange transaction with Linq Context.








MyContextDataContext objContext = new MyContextDataContext();
using (System.Transactions.TransactionScope tScope
        = new System.Transactions.TransactionScope(TransactionScopeOption.Required))
{
     objContext.Order.InsertOnSubmit(Order);
     objContext.OrderDetails.InsertOnSumbit(OrderDetails);
     objContext.SubmitChanges();
     tScope.Complete();
}

No comments:

Post a Comment