title: NullReferenceException with Entity Framework and Multithreading
body: <p>I'm saving data using the Entity Framework in a Parallel.ForEach loop.
  Knowing that the EF is not thread-safe, I instanciate an entity context for each of my thread.</p>
  
  <p>1- Is it safe?
  It seems to be as I see in these posts:</p>
  
  <p><a href="https://stackoverflow.com/questions/7176303/entity-framework-multiple-threads-lazy-load">Entity Framework + Multiple Threads + Lazy Load</a></p>
  
  <p><a href="https://stackoverflow.com/questions/5491869/is-it-safe-to-use-one-entity-framework-context-per-thread-yes-how">Is it safe to use one Entity Framework Context per thread? ... yes? how?</a></p>
  
  <p>2-There is an exception during the creation of my context, but only one time out of 3 and I can't found out why.</p>
  
  <p>Here is my code creating the context:</p>
  
  <pre><code>public partial class Entities
  {
      private static Entities mfgEntities = new Entities();
      private static readonly Dictionary&lt;int,Entities&gt;  ThreadContexts = new Dictionary&lt;int, Entities&gt;();
  
      public static Entities Context
      {
          get
          {
              if (HttpContext.Current != null)
              {
                  string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
                  if (!HttpContext.Current.Items.Contains(objectContextKey))
                  {
                      HttpContext.Current.Items.Add(objectContextKey, new Entities());
                  }
                  return HttpContext.Current.Items[objectContextKey] as Entities;
              }
              else
              {
                  int threadId = Thread.CurrentThread.ManagedThreadId;
                  if (!ThreadContexts.ContainsKey(threadId))
                  {
                      try
                      {
                          ThreadContexts.Add(threadId, new Entities());
                      }
                      catch (Exception ex)
                      {
                          throw new Exception("Erreur lors de la création de l'entity context");
                      }
                  }
                  return ThreadContexts[threadId];
              }
              return mfgEntities;
          }
      }
  }
  </code></pre>
  
  <p>It throws a NullReferenceException on line :</p>
  
  <pre><code>ThreadContexts.Add(threadId, new Entities());
  </code></pre>
  
  <p>And ThreadContexts, threadId and the new Entities are not null.</p>
  
  <p>I thank you for your help.</p>