title: Entity Framework, Multi Threading, and Transactions
body: <p>I have an application that reads data from one database, and transforms that data into a new form and writes it into a new database. Some of the tables in the new database are made from multiple tables in the old database so there is a large amount of reading and writing going on. Here is the basic concept of the system:</p>
  
  <pre><code>public void TransferData()
  {
      OldEntities oldContext = new OldEntities()
      NewEntities newContext = new NewEntities()
      using(var transaction = newContext.Database.BeginTransaction())
      {
          try{
              TransferTable(oldContext, newContext);
          } catch (Exception e) {
              transaction.Rollback();
          }
      }
  }
  
  public void TransferTable(OldEntities oldContext, NewEntities newContext)
  {
      List&lt;Entity1&gt; mainTable = oldContext.Where();
      Parallel.ForEach(mainTable, (row) =&gt;
          {
              using(NewEntities anotherNewContext = new NewContext())
              {
                  anotherNewContext.Database.UseTransaction(newContext.Database.CurrentTransaction.UnderlyingTransaction);
                  // Do Work
              }
          });
  }
  </code></pre>
  
  <p>This causes the following exception:</p>
  
  <blockquote>
    <p>The transaction passed in is not associated with the current connection. Only transactions associated with the current connection may be used.</p>
  </blockquote>
  
  <p>How can I get around this. The transaction will always be coming from a different EF context but I need them all to share the same transaction. I couldn't find a way to create the new context as a "child" of the original and I am trying to avoid creating a transaction entirely separate from the EF context. Any suggestions?</p>