title: EF Where(x => x.ColumnVal == 1) vs FirstOrDefault(x => x.Column == 1)
body: <p>I had a LINQ query that loads a hierarchy of objects like the following.</p>
  
  <p><strong>Query #1</strong></p>
  
  <pre><code>var result = db.Orders
                 .Include("Customer")
                 // many other .Include() here
                 .FirstOrDefault(x =&gt; x.Customer.CustomerId == 1 &amp;&amp;
                                      x.OrderId == orderId);
  </code></pre>
  
  <p>I was having <strong>MAJOR performance problem</strong> with it.<br />
  The CPU usage was near 100% and memory usage was very high.
  <br /><br /></p>
  
  <p>And I tweaked it to the following and the performance problem was fixed.</p>
  
  <p><strong>Query #2</strong></p>
  
  <pre><code>var result = db.Orders
                 .Include("Customer")
                 // many other .Include() here
                 .Where(x =&gt; x.Customer.CustomerId == 1 &amp;&amp;
                             x.OrderId == orderId)
                 .FirstOrDefault();
  </code></pre>
  
  <p><br />
  <br />
  I just want to confirm my suspicion.<br />
  Query #1 is probably looping through all my records <strong>in memory</strong> looking for a matching record<br />
  <strong>vs</strong><br />
  Query #2 filters the records on the Database and then getting the first record only.<br /><br /></p>
  
  <p>Is that why the <strong>Query #1</strong> has performance problems?<br /><br /></p>
  
  <p>Just to be safe, do I need to use the <code>.Select(x =&gt; x)</code> before the <code>.FirstOrDefault()</code>?</p>
  
  <p><strong>Query #3</strong></p>
  
  <pre><code>var result = db.Orders
                 .Include("Customer")
                 // many other .Include() here
                 .Where(x =&gt; x.Customer.CustomerId == 1 &amp;&amp;
                             x.OrderId == orderId)
                 .Select(x =&gt; x)
                 .FirstOrDefault();
  </code></pre>