title: Is a DbContext per thread in Parallel.ForEach safe?
body: <p>I am working a contract right now to increase the performance of a back end services for a modern SaaS SPA web app that is using EF 6 as their ORM. The first thing I proposed was to introduce some multi-threading to their  back end service which is currently running single threaded. The lead software engineer has indicated we cannot do that because EF 6 is not thread-safe. </p>
  
  <p>I am no expert on Entity Framework. My ORM of choice is XPO by DevExpress and I have done something similar to what is proposed below without issue using that ORM. Is this pattern inherently not safe using EF 6?</p>
  
  <pre><code>int[] ids;
  using(var db = new ApplicationDbContext())
  {
      // query to surface id's of records representing work to be done
      ids = GetIdsOfRecordsRepresentingSomeTask(db);
  }
  
  Parallel.ForEach(ids, id =&gt; { 
      using(var db = new ApplicationDbContext())
      {
          var processor = new SomeTaskProcessor(db, id);
          processor.ExecuteLongRunningProcessThatReadsDbAndCreatesSomeNewRecords();
          db.SaveChanges();
      }
  });
  </code></pre>
  
  <p>I have researched this, and I agree that DbContext is not thread-safe. The pattern I propose does use multiple threads, but a single DbContext is only every accessed by a single thread in a single-threaded fashion. The lead is telling me that DbContext is essentially a singleton under the covers and this code would ultimately mess up the database. I can't find anything to support this claim. Is the lead right on this?</p>
  
  <p>Thanks</p>