Multiple SubmitChanges and transaction rollback using Linq To SQL

dstr picture dstr · Oct 28, 2009 · Viewed 8.7k times · Source

I'm using TransactionScope to submit data in Linq to SQL. My question is, if I use multiple SubmitChanges in the same scope, will all scope roll back in case of an error or just the changes made after the last SubmitChanges? For example:

using (TransactionScope trans = new TransactionScope())
{
    using (dbDataContext db = new dbDataContext())
    {
        try
        {
            //do some insert
            db.SubmitChanges();

            //do some updates
            db.SubmitChanges();

            trans.Complete();
        }
        catch(Exception ex){}
    }
}

If update SubmitChanges throws an exception, will the insert SubmitChanges roll back too?

Answer

Dave Markle picture Dave Markle · Oct 28, 2009

ALL changes will roll back, not just the one from the last SubmitChanges().

You will often need to use this pattern when you have data that depends on other data -- like if you need to create an object and get it's auto-generated ID in order to do something else (though L2SQL supports that with one SubmitChanges call in most scenarios by just creating the object, but I digress...).