Note that there are some explanatory texts on larger screens.

plurals
  1. POSum in Linq to Sql not returning a value
    text
    copied!<p>I'm looking for a query to return the sum of all payments against an invoice ID - however, if there are no payments noted, the query below returns null. Is there any way of it returning 0 instead of null? I've tried adding ?? 0 at the end, but get the message <code>Operator ?? cannot be applied to operands of type decimal and int</code></p> <p>AmountAllocated is of type Decimal:</p> <pre><code>public decimal AmountAllocated { get; set; } </code></pre> <p>Thanks, Mark</p> <p>The following returns null for Sum when there are no payment rows found:</p> <pre><code> var invoiceVM = from i in db.Invoices where i.UserName==userName select new NewInvoiceViewModel { InvoiceId = i.InvoiceId, SumPayments = db.PaymentInvoices.Where(pi =&gt; pi.InvoiceId == i.InvoiceId) .Select(pi =&gt; pi.AmountAllocated).Sum() }; </code></pre> <p>The following results in the <code>Operator ?? cannot be applied to operands of type decimal and int</code> error:</p> <pre><code> var invoiceVM = from i in db.Invoices where i.UserName==userName select new NewInvoiceViewModel { InvoiceId = i.InvoiceId, SumPayments = db.PaymentInvoices.Where(pi =&gt; pi.InvoiceId == i.InvoiceId) .Sum(pi =&gt; pi.AmountAllocated) ?? 0 }; </code></pre> <p>If there have been payments made, then AmountAllocated correctly returns the sum of those payments - just it returns null if there are no payment rows found.</p> <p>You can see from the screenshot below, the first record has a payment, and shows correct as 10 (decimal) - the second record has no payments, and shows as null (decimal).</p> <p><img src="https://i.stack.imgur.com/mRklk.png" alt="screenshot"></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