Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In your repository, you can use <code>ObjectQuery.ToTraceString</code> to see what SQL is getting executed before you return your objects.</p> <p>You are returning all of the actual <code>Trap</code> objects deployed in 2012 from your repository find method, instead of an IQueryable AND you are not eager loading <code>TrapActivities</code>. That means as you enumerate through the results in <code>Select</code> to create your view model, you are sending a new query to the DB for each <code>Trap</code> to get it's <code>TrapActivities</code>.</p> <p><strong>Update 1</strong></p> <p>I think you will need to implement a specific query in your repository for this. </p> <pre><code>var q = from t in traps where t.DeploymentYear == 2012 select new TrapFirstDeployment { Trap = t, DeploymentActivity = t.TrapActivities.Where(ta=&gt;ta.FirstOrDefault(a=&gt;a.ActivityType=1)) }; return q.Where(tfd=&gt;tfd.DeploymentActivity != null); </code></pre> <p><strong>Explanation</strong></p> <p>The reason your initial query was slow is because EF doesn't eager load child relationships unless you tell it to. Lazy Loading is on by default. Since you don't tell it to load <code>TrapActivities</code> with your <code>Trap</code> in your repository, it waits until you access it the first time to load them. This is great you need the trap but not the activities because it reduces traffic to/from the DB. However, in some situations you need them. In that case you can force an eager load by adding <code>Include</code> in your query. e.g., </p> <pre><code>var q = from t in this.objectSet.Include('TrapActivities') select t; </code></pre> <p>This loads ALL of the <code>TrapActivities</code> with the trap in one query. However, in your case, you only need the first deployment activity which is why I created the <code>TrapFirstDeployment</code> class. This way, EF should only grab the first deployment activity.</p> <p><strong>Update 2</strong></p> <p>You should also change the parameter on the <code>Find</code> method on your repository to <code>Expression&lt;Func&lt;T,Boolean&gt;&gt;</code> to match the <code>IQueryable.Where</code> signature. <code>IEnumerable.Where</code> uses <code>Func&lt;T,Boolean&gt;</code> so that is why <code>objectSet</code> is getting converted to an <code>IEnumberable</code> before <code>Where</code> is called.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload