title: Entity Framework + LINQ + "Contains" == Super Slow?
body: <p>Trying to refactor some code that has gotten really slow recently and I came across a code block that is taking 5+ seconds to execute.</p>
  
  <p>The code consists of 2 statements:</p>
  
  <pre><code>IEnumerable&lt;int&gt; StudentIds = _entities.Filters
                      .Where(x =&gt; x.TeacherId == Profile.TeacherId.Value &amp;&amp; x.StudentId != null)
                      .Select(x =&gt; x.StudentId)
                      .Distinct&lt;int&gt;();
  </code></pre>
  
  <p>and</p>
  
  <pre><code>_entities.StudentClassrooms
                      .Include("ClassroomTerm.Classroom.School.District")
                      .Include("ClassroomTerm.Teacher.Profile")
                      .Include("Student")
                      .Where(x =&gt; StudentIds.Contains(x.StudentId)
                      &amp;&amp; x.ClassroomTerm.IsActive
                      &amp;&amp; x.ClassroomTerm.Classroom.IsActive
                      &amp;&amp; x.ClassroomTerm.Classroom.School.IsActive
                      &amp;&amp; x.ClassroomTerm.Classroom.School.District.IsActive).AsQueryable&lt;StudentClassroom&gt;();
  </code></pre>
  
  <p>So it's a bit messy but first I get a Distinct list of Id's from one Table (Filters), then I query another Table using it.</p>
  
  <p>These are relatively small tables, but it's still 5+ seconds of query time.</p>
  
  <p>I put this in LINQPad and it showed that it was doing the bottom query first then running 1000 "distinct" queries afterwards.</p>
  
  <p>On a whim I changed the "StudentIds" code by just adding .ToArray() at the end.  This improved the speed 1000x ... it now takes like 100ms to complete the same query.</p>
  
  <p>What's the deal?  What am I doing wrong?</p>