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.
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 a good link that providing good details about maintaing Transaction in LINQ to SQL
ReplyDeletehttp://www.a2zmenu.com/LINQ/Maintain%20Transaction%20in%20LINQ%20to%20SQL.aspx
@Anonymous
ReplyDeleteThat is a old way of doing this.
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