开发者

handle transaction in Linq to sql

开发者 https://www.devze.com 2023-02-06 16:28 出处:网络
I am implementing the asp.net MVC web application, where i am using the Linq to Sql to manipulate the data in database. but in my one of action, i want to insert multiple table entries which are depen

I am implementing the asp.net MVC web application, where i am using the Linq to Sql to manipulate the data in database. but in my one of action, i want to insert multiple table entries which are depends upon each other by referring previous insertion Id's. So i just wnat to know how t开发者_开发技巧o handle the transaction, like begin transaction, commit,rollback and all like in ADO.net. how to manage this. what if one of insertion get crashed in the middle of manipulation?

Note:- I am not using the Stored procedures here. I am using Lambda expressions and methods. Also these are use in different manager classes. Example: For Create Subject - used method in SubjectManager class to insert subject infor, that returns subject Id. within this subjectid i am inserting the let say its chapters with another method in manager class as ChapterManager. which again returns the ChapterId, on base of this chapeter Id , inserting the Topics of chapter. that again uses Topic manager same like above.in each manger class i am creating dataContext object for the same. and I am controlling all this within a single action in my controller. but worrying about the transaction management. how I can use here ?


The DataContext already includes an embedded transaction object. For example, let's say you are placing a new order for a customer. You can set up your model so that the following code updates both the Customer AND Order table with a single SubmitChanges. As long as a foreign key relationship exists between the two tables, the embedded transaction object handles both the Customer update and the Order insert in the same transaction. Using a TransactionScope object to encase a single DataContext is redundant:

using (DataContext dc = new DataContext())
{
    Order order = new Order();

    order.ProductID = 283564;
    order.Quantity = 7;
    order.OrderDate = DateTime.Now;

    Customer customer = dc.Customers.Single(c => c.CustomerID == 6);

    customer.LastUpdate = order.OrderDate;
    customer.Orders.Add(order);

    dc.SubmitChanges();
}


using(TransactionScope scope = new TransactionScope())
{
    using(DataContext ctx = new MyDataContext())
    {
        ctx.Subject.Add(subject);
        Chapter chapter = new Chapter();
        chapter.SubjectId = subject.Id;
        ctx.SubmitChanges();
        ctx.Chapter.Add(chapter);
        ctx.SubmitChanges();
        scope.Complete() // if it all worked out
    }
}

From the System.Transactions namespace I believe.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号