Denis
Denis

Reputation: 3759

DataContext.Submit and TransactionScope

Please explain me pseudocode below.

My idea is: 3-nd SubmitChanges will commit o.Status and will not commit o.TransactionId, and my object will get corrupted in database (I mean it will not be consistent anymore).

XDataContext DB = .....; 
XOrder o = DB.XOrders.Single(.......);

try
{
    using (var t = new TransactionScope())
    {
        o.Status = XOrderStatus.Completed;
        DB.SubmitChanges(); // 1
        string s = null;
        s.Trim(); // crash here;
        o.TransactionId = ......; // some calculations here
        DB.SubmitChanges(); // 2
        t.Complete();
    }
}
catch (Exception ex)
{
    XEvent e = new XEvent();
    e.Type = XEventType.Exception;
    e.Data = .........; // some calculations here
    DB.XEvents.InsertOnSubmit(e);
    DB.SubmitChanges(); // 3
}

Is it any 'best practices' for my case?

Upvotes: 0

Views: 550

Answers (1)

Amy B
Amy B

Reputation: 110221

Is it any 'best practices' for my case?

Yes. Use one DataContext instance per unit of work.

catch (Exception ex)
{
    XEvent e = new XEvent();
    e.Type = XEventType.Exception;
    e.Data = .........; // some calculations here
   using (XDataContext dc2 = new XDataContext())
   {
    dc2.XEvents.InsertOnSubmit(e);
    dc2.SubmitChanges(); // 3
   }
}

Upvotes: 1

Related Questions