title: Optimize Entity framework Query, avoid lazy-loading
body: <p>I have a linq query that takes a couple of seconds(~2.6s) to run. But i want to reduce that to as little as possible.</p>
  
  <p>I only require reading so I've included the .AsNoTracking() behavior.</p>
  
  <p>I have also tested the query without include statements, but my operations after the get request slowed it down further so i left the includes to optimize my other operations.</p>
  
  <p><strong>The main goal is to reduce the Database talk, therefor the ToList(),Include statements.</strong></p>
  
  <p>Code:</p>
  
  <pre><code>var obj = _context.MyContextModel.AsNoTracking()
              .Where(x =&gt; x.CategoryList.Model.Id == 1)
              .Where(x =&gt; x.CategoryList.Model.TypeId == 1)
              .Where(x =&gt; x.Year.Select(y=&gt;y.Datetime).Any(item =&gt; item.Year == 2010))
              .Include(x =&gt; x.LinkedMarket).AsNoTracking()
              .Include(x =&gt; x.Year).AsNoTracking()
              .Include(x =&gt; x.CategoryList).AsNoTracking()
              .Include(x =&gt; x.CategoryList.Model).AsNoTracking();
  
  return obj.AsParallel().ToList();
  </code></pre>
  
  <p>This operation usually returns about 1000-2000 MyContextModel records, not including the "includes"</p>
  
  <p>How can i optimize this further?
  Should i load objects to a container class? or another solution?</p>
  
  <p><strong>Update</strong></p>
  
  <pre><code>_context.Configuration.ProxyCreationEnabled = false;
  _context.Configuration.LazyLoadingEnabled = false;
  var obj = _context.MyContextModel.AsNoTracking()
                  .Where(x =&gt; x.CategoryList.Model.Id == 1)
                  .Where(x =&gt; x.CategoryList.Model.TypeId == 1)
                  .Where(x =&gt; x.LinkedMarket.FirstOrDefault(mar=&gt;mar.MarketID == marketId) != null)
                  .Include(x =&gt; x.Year).AsNoTracking()
                  .Include(x =&gt; x.CategoryList).AsNoTracking()
                  .Include(x =&gt; x.CategoryList.Model).AsNoTracking();
  
  return obj.AsParallel().ToList();
  </code></pre>
  
  <p>Basically i've removed where clause which filter the year(I do that later, therefor the include of the year)
  I've added a Where clause that specify market from the getgo.</p>
  
  <p>I've removed the Include which contained market.</p>
  
  <p>One big performance thief was the Linked market(i don't know exactly why, something EF didn't like.)</p>
  
  <p>This reduced the query to about a average on 0,4 seconds.
  And the whole operation set from 4+ seconds to a stunning 0,7 seconds.</p>