Search code examples
linq-to-sqltransactionscopemsdtc

Am I using TransactionScope and DataContext properly?


What if I new up some DataContexts, read some data, and then only wrap the SubmitChanges in a TransactionScope?

string conn1 = GetConn1();
string conn2 = GetConn2();
using (DataContext1 dc1 = new DataContext1(conn1))
{
  List<Customer> customers = ReadSomeData(dc1);
  ModifySomeCustomers(customers);  //performs local modification to Customer instances

  using (DataContext2 dc2 = new DataContext2(conn2))
  {
    List<Order> orders = ReadSomeData(dc2);
    ModifySomeOrders(orders); //performs local modification to Order instances

    using (TransactionScope scope = new TransactionScope())
    {
      dc1.SubmitChanges();
      dc2.SubmitChanges();
      scope.Complete();
    }
  }
}

The first SubmitChanges call is expected to fetch a connection from the pool and enlist that connection in the scope. MS DTC is enabled - the second SubmitChanges call is expected to promote the transaction to "distributed", fetch a connection from the pool and enlist that connection in the scope.

I'm concerned that ReadSomeData may have left the connection open, so SubmitChanges doesn't fetch a connection from the pool, and therefore doesn't enlist the connection in the scope.


Solution

  • SubmitChanges will participate in the TransactionScope.

    If SubmitChanges finds an ambient transaction it enlists to that transaction, otherwise it creates a transaction itself for the lifetime of the SubmitChanges method.

    There is an MSDN Article about the transaction handling in SubmitChanges.