Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat would be a reasonably fast way to code this sql query in c#?
    primarykey
    data
    text
    <p>I have this SQL query:</p> <pre><code>select sum(h.nbHeures) from Heures h join HeuresProjets hp on h.HpGuid=hp.HPId join ActivityCodes ac on h.Code=ac.ActivityId join MainDoeuvre mdo on ac.ActivityId=mdo.CodeGuid where hp.ExtraGuid = '61E931C8-3268-4C9C-9FF5-ED0213D348D0' and mdo.NoType = 1 </code></pre> <p>It runs in less than a second, which is good. My project uses LINQ to entities to get data. This (very similar to the sql) query is terribly slow, taking more than a minute.</p> <pre><code> var result = (from hp in this.HeuresProjets join h in ctx.Heures on hp.HPId equals h.HpGuid join ac in ctx.ActivityCodes on h.Code equals ac.ActivityId join mdo in ctx.MainDoeuvre on ac.ActivityId equals mdo.CodeGuid where hp.ExtraGuid == this.EntityGuid &amp;&amp; mdo.NoType == (int)spType select h.NbHeures).Sum(); total = result; </code></pre> <p>I tried using nested loops instead. It's faster but still slow (~15 seconds).</p> <pre><code>foreach (HeuresProjets item in this.HeuresProjets) { foreach (Heures h in ctx.Heures.Where(x =&gt; x.HpGuid == item.HPId)) { if (h.ActivityCodes != null &amp;&amp; h.ActivityCodes.MainDoeuvre.FirstOrDefault() != null &amp;&amp; h.ActivityCodes.MainDoeuvre.First().NoType == (int)type) { total += h.NbHeures; } } } </code></pre> <p>Am I doing something obviously wrong? If there's no way to optimize this I'll just call a stored procedure but I would really like the keep the logic in the code.</p> <p><strong>EDIT</strong></p> <p>I modified my query according to IronMan84's advice.</p> <pre><code>decimal total = 0; var result = (from hp in ctx.HeuresProjets join h in ctx.Heures on hp.HPId equals h.HpGuid join ac in ctx.ActivityCodes on h.Code equals ac.ActivityId join mdo in ctx.MainDoeuvre on ac.ActivityId equals mdo.CodeGuid where hp.ExtraGuid == this.EntityGuid &amp;&amp; mdo.NoType == (int)spType select h); if(result.Any()) total = result.Sum(x=&gt;x.NbHeures); </code></pre> <p>This almost works. It runs fast and gives back a decimal but:<br> 1. It's not the right value<br> 2. The result is clearly cached because it returns the exact same value with different parameters. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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