title: Sum() Returns null in Entity Framework Query
body: <p>I have a big Entity Framework query that includes these lines.</p>
  
  <pre><code>var programs = from p in Repository.Query&lt;Program&gt;()
                 where p.OfficeId == CurrentOffice.Id
                 let totalCharges = p.ProgramBillings.Where(b =&gt; b.Amount &gt; 0 &amp;&amp; b.DeletedDate == null).Select(b =&gt; b.Amount).Sum()
                 let totalCredits = p.ProgramBillings.Where(b =&gt; b.Amount &lt; 0 &amp;&amp; b.DeletedDate == null).Select(b =&gt; -b.Amount).Sum()
                 let billingBalance = (totalCharges - totalCredits)
  </code></pre>
  
  <p>When I materialize the data, I get the following error:</p>
  
  <blockquote>
    <p>The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.</p>
  </blockquote>
  
  <p>If I change my query as follows (added in two type casts), the error goes away.</p>
  
  <pre><code>var programs = from p in Repository.Query&lt;Program&gt;()
                 where p.OfficeId == CurrentOffice.Id
                 let totalCharges = (decimal?)p.ProgramBillings.Where(b =&gt; b.Amount &gt; 0 &amp;&amp; b.DeletedDate == null).Select(b =&gt; b.Amount).Sum()
                 let totalCredits = (decimal?)p.ProgramBillings.Where(b =&gt; b.Amount &lt; 0 &amp;&amp; b.DeletedDate == null).Select(b =&gt; -b.Amount).Sum()
                 let billingBalance = (totalCharges - totalCredits)
  </code></pre>
  
  <p>I do not understand this. <code>ProgramBilling.Amount</code> is a non-nullable Decimal. If I hover over the <code>Sum()</code> call, Intellisense says it returns type Decimal. And yet additional tests confirmed that, in my second version, <code>totalCharges</code> and <code>totalCredits</code> are both set to null for those rows where <code>ProgramBillings</code> has no data.</p>
  
  <p>Questions:</p>
  
  <ol>
  <li><p>I understood <code>Sum()</code> returned 0 for an empty collection. Under what circumstances is this not true?</p></li>
  <li><p>And if sometimes that is not true, then why when I hover over <code>Sum()</code>, Intellisense shows it returns type Decimal and not Decimal? It appears Intellisense had the same understanding that I had.</p></li>
  </ol>
  
  <p><strong>EDIT:</strong></p>
  
  <p>It would seem that an easy fix is to do something like <code>Sum() ?? 0m</code>. But that's illegal, giving me the error:</p>
  
  <blockquote>
    <p>Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'</p>
  </blockquote>