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 Operator ?? cannot be applied to operands of type decimal and int
AmountAllocated is of type Decimal:
public decimal AmountAllocated { get; set; }
Thanks, Mark
The following returns null for Sum when there are no payment rows found:
var invoiceVM = from i in db.Invoices
where i.UserName==userName
select new NewInvoiceViewModel
{
InvoiceId = i.InvoiceId,
SumPayments =
db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
.Select(pi => pi.AmountAllocated).Sum()
};
The following results in the Operator ?? cannot be applied to operands of type decimal and int
error:
var invoiceVM = from i in db.Invoices
where i.UserName==userName
select new NewInvoiceViewModel
{
InvoiceId = i.InvoiceId,
SumPayments =
db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
.Sum(pi => pi.AmountAllocated) ?? 0
};
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.
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).