Thursday, May 20, 2010

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();
}
Here it will commit transaction only if using blocks will run successfully. Hope this will help you.

Shout it
kick it on DotNetKicks.com
Share:

3 comments:

  1. Here a good link that providing good details about maintaing Transaction in LINQ to SQL


    http://www.a2zmenu.com/LINQ/Maintain%20Transaction%20in%20LINQ%20to%20SQL.aspx

    ReplyDelete
  2. @Anonymous

    That is a old way of doing this.

    ReplyDelete
  3. Wow! You have managed to transform a very helpful thought into reality. I was looking for someone who could help me in managing my assets. And your site has everything I needed for my asset protection. Not only your site but also your marketing team is very helpful to me. I thank you for that. anonymous transactions

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews