0

我正在寻找一个查询,以根据发票 ID 返回所有付款的总和 - 但是,如果没有记录付款,则下面的查询将返回 null。有什么方法可以返回 0 而不是 null 吗?我试过添加??0 结尾,但得到消息Operator ?? cannot be applied to operands of type decimal and int

AmountAllocated 是 Decimal 类型:

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(十进制)。

截屏

4

2 回答 2

1

您可以尝试测试以查看是否有任何要返回的行。

{
       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-24T18:31:34.447 回答
0

我相信这是因为在 SQL 中所有数据类型都可以为空,但在 C# 中却不是这样。尝试强制枚举您的付款发票,然后再使用.ToList()

SumPayments = db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
                                .Select(pi => pi.AmountAllocated)
                                .ToList()
                                .Sum()

更新:尝试将查询编写为从 Invoices 到 PaymentInvoices 的联接,并改为按 InvoiceId 分组。我认为您遇到的问题是因为您试图将聚合总和作为子查询执行。

于 2013-05-24T15:10:42.523 回答