首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linq to Sql中的Sum未返回值

问Linq to Sql中的Sum未返回值
EN

Stack Overflow用户
提问于 2013-05-24 22:28:23
回答 2查看 1.6K关注 0票数 0

我正在寻找一个查询,根据发票ID返回所有付款的总和-但是,如果没有记录付款,下面的查询将返回null。有没有办法让它返回0而不是null?我尝试在末尾添加??0,但收到消息Operator ?? cannot be applied to operands of type decimal and int

AmountAllocated的类型为小数:

代码语言:javascript
复制
public decimal AmountAllocated { get; set; }

谢谢,马克

当没有找到付款行时,以下代码将为Sum返回null:

代码语言:javascript
复制
 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错误:

代码语言:javascript
复制
  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 (小数)。

​

​

EN

回答 2

Stack Overflow用户

发布于 2013-05-25 02:31:34

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

代码语言:javascript
复制
{
       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。

票数 1
EN

Stack Overflow用户

发布于 2013-05-24 23:10:43

我相信这是因为在SQL中,所有数据类型都是可以为空的,但在C#中并非如此。尝试在使用.ToList()对付款发票进行合计之前强制枚举这些发票

代码语言:javascript
复制
SumPayments = db.PaymentInvoices.Where(pi => pi.InvoiceId == i.InvoiceId)
                                .Select(pi => pi.AmountAllocated)
                                .ToList()
                                .Sum()

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16737369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档