Update many child objects in one transaction

Update many child objects in one transaction

Old forum URL: forums.lhotka.net/forums/t/4855.aspx


tchimev posted on Friday, May 16, 2008

I'm using CSLA .net and Linq To SQL.
I have a ProductList : BusinessListBase<ProductList, Product>
I changed the values of two Products form the list.

using (System.Transactions.TransactionScope ts = new  System.Transactions.TransactionScope())
{
          DataPortal.Update<ProductList>(pList);
          ts.Complete();
}

I use the code above to save the changes into DB.

Here is the DataPortal method from the Product class:
 private void Child_Update()
{
       using (var ctx = ContextManager<LinqDataContext>.GetManager("DBname"))
      {
                ctx.DataContext.Products.Attach(this.MapToLinq(), this.IsDirty);
                ctx.DataContext.SubmitChanges();
      }
}

I expected to save it in one transaction but I got an error it requires a Distributed transaction.
Is there a way to save changes in one local transaction?
Without transaction everything works fine.


ajj3085 replied on Friday, May 16, 2008

The only time you're creating a connection is in the child update.  Since no connection exists, one is created.  At the end of the using block, since only one object was using the connection, it's closed.  Loop around again, and the same thing happens.

Leave the code in your child alone, but change the parents data portal code to this:

using (var ctx = ContextManager<LinqDataContext>.GetManager("DBname"))
      {
    DataPortal.Update<ProductList>(pList);
}

This will create the connection.  The ContextManager in the CHILD object will pick up that a connection already exists, and use that.  It also won't close the connection because the parent still has a reference to it.

HTH
Andy

ajj3085 replied on Friday, May 16, 2008

Also, there's no need to manually use the TransactionScope.  You can use the Transactional attribute with an TransactionScope value to do the same thing, without requiring you to code it.

tchimev replied on Saturday, May 17, 2008

Thank you for your answer.

Copyright (c) Marimer LLC