title: Very slow performance on LINQ subquery
body: <p>I am facing a performance issue when doing a LINQ subquery in C#.
  The query is as follows:</p>
  
  <pre><code>var _result = _db.Prices
              .Join(_db.Vendors,
              e =&gt; e.VendorId,
              v =&gt; v.VendorId,
              (e, v) =&gt; new {
                  TotalPrice = e.TotalPrice,     
                  Vendor = v.Title,               
                  AmountPaid = _db.Amounts
                      .Where(p =&gt; p.PrId == e.PrId )
                      .GroupBy(p =&gt; p.PrId )
                      .Select(grp =&gt; (decimal?)grp.Sum(k =&gt; k.AmountPaid) ?? 0M)    
                      .FirstOrDefault()  
              });
  </code></pre>
  
  <p>Prices, Vendors and Amounts are Entity Framework objects.</p>
  
  <p>Firstly I am doing a join of Prices to Vendors table on VendorId and on the result I am adding a calculated field AmountPaid. The result is a subquery which returns the sum of AmountPaid column in Amounts table for the given record matched by PrId index.
  All the above is returned as a JSON object in ASP.NET web api.</p>
  
  <p>The result of the above for the records in a database is only 1992 rows.
  The above command neeeds about 20 seconds to return the result. If I remove the AmountPaid calculation it needs only 1 second.</p>
  
  <p>If I run the equivalent SQL command in SQL Server studio it needs only half a second with the AmountPaid calculation included:</p>
  
  <pre><code>SELECT Prices.*, Vendors.Title, 
  AmountPaid = (SELECT SUM(AmountPaid) from Amounts where Amounts.PrId = Prices.PrId GROUP BY PrId) FROM Amounts 
  INNER JOIN Vendors ON Amounts.VendorId = Vendors.VendorId
  </code></pre>
  
  <p>Is there a way to fix this?
  I cannot understand the issue since the SQL command does not have an issue in execution.
  Is there an error on the LINQ syntax, or another way to get in LINQ the same result set?</p>