我正在寻找一个查询,根据发票ID返回所有付款的总和-但是,如果没有记录付款,下面的查询将返回null。有没有办法让它返回0而不是null?我尝试在末尾添加??0,但收到消息Operator ?? cannot be applied to operands of type decimal and int
AmountAllocated的类型为小数:
public decimal AmountAllocated { get; set; }谢谢,马克
当没有找到付款行时,以下代码将为Sum返回null:
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()
};以下结果会导致Operator ?? cannot be applied to operands of type decimal and int错误:
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
};如果已经进行了付款,则AmountAllocated会正确地返回这些付款的总和-如果没有找到付款行,则返回null。
您可以从下面的屏幕截图中看到,第一条记录有付款,并显示正确为10 (十进制)-第二条记录没有付款,显示为null (小数)。

发布于 2013-05-25 02:31:34
您可以尝试测试以查看是否有要返回的行。
{
InvoiceId = i.InvoiceId,
SumPayments =
db.PaymentInvoices.Any(pi => pi.InvoiceId == i.InvoiceId)
? db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
.Select(pi => pi.AmountAllocated).Sum()
: 0
};另一种选择是使用SumPayments.GetValueOrDefault(),它将返回值或0。
发布于 2013-05-24 23:10:43
我相信这是因为在SQL中,所有数据类型都是可以为空的,但在C#中并非如此。尝试在使用.ToList()对付款发票进行合计之前强制枚举这些发票
SumPayments = db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
.Select(pi => pi.AmountAllocated)
.ToList()
.Sum()UPDATE:尝试将查询编写为从Invoices到PaymentInvoices的联接,并按InvoiceId分组。我认为您遇到的问题是因为您试图将聚合和作为子查询来执行。
https://stackoverflow.com/questions/16737369
复制相似问题