title: Entity Framework "Unexpected Connection State" Exception
body: <p>After three hours of debugging and searching, I'm hoping someone here has an answer. Entity Framework (using MySQL) throws the following exception if I call the following function quickly in succession (e.g. &lt; 0.1 seconds apart).</p>
  
  <blockquote>
    <p>System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.</p>
  </blockquote>
  
  <p>However, sometimes the function works without any problems. The exception is thrown on the first <code>ToList()</code> call:</p>
  
  <pre><code>void InsertOrUpdateMaterials(List&lt;Material&gt; materials)
  {
      var id = GetUserId();
      var materialIds = materials.Select(x =&gt; x.MaterialId).ToList();
  
      // Remove old materials from DB
      var oldMaterials = Db.Materials.Where(p =&gt; p.CreatedBy == id &amp;&amp; 
              materialIds.Contains(p.MaterialId)).ToList(); // exception
      Db.Materials.RemoveRange(oldMaterials);
      Db.SaveChanges();
  
      // Replace previous materials with the new ones in list
      Db.Materials.AddRange(materials);
      Db.SaveChanges();
  }
  </code></pre>
  
  <p>Oddly, this error never occurred on the development server, so I looked into possible configuration issues to no avail.</p>
  
  <p>Sometimes, Entity Framework throws:</p>
  
  <blockquote>
    <p>System.Data.Entity.Core.EntityCommandExecutionException: There is already an open DataReader associated with this Connection which must be closed first.</p>
  </blockquote>
  
  <p>Again pointing to the <code>ToList()</code> call. Any ideas?</p>