当没有要求和的内容时,Linq.Sum()函数将失败

本文关键字:Sum Linq 函数 失败 求和 和的 | 更新日期: 2023-09-27 17:50:08

运行以下Linq查询时

ViewBag.AmountThisYear = db.Bookings
            .Where(p => p.Id == id && 
                        p.StartDate.Year == DateTime.Now.Year)
            .Sum(t => t.Price);

当在where子句中没有返回结果时,我得到了以下错误

转换为值类型"System.Decimal"失败,因为物化值为null。结果类型的泛型参数或者查询必须使用可为null的类型。

应如何编写Sum以应对这种情况

当没有要求和的内容时,Linq.Sum()函数将失败

由于不返回任何行,因此无法求和。您可以使用DefaultIfEmpty:

ViewBag.AmountThisYear = db.Bookings
            .Where(p => p.Id == id && 
                        p.StartDate.Year == DateTime.Now.Year)
            .Select(t => t.Price)
            .DefaultIfEmpty(0)
            .Sum();

如果计算字段不可为null,则需要首先强制转换为null进行计算。因此,变化如下:

ViewBag.AmountThisYear = db.Bookings
            .Where(p => p.Id == id && 
                        p.StartDate.Year == DateTime.Now.Year)
            .Sum(t => (decimal?)t.Price) ?? 0m;

另外,添加联合运算符(??(将null转换为0。

decimal sum = 0;
var booking = db.Bookings
        .Where(p => p.Id == id && 
                    p.StartDate.Year == DateTime.Now.Year);

if(bookings.Any())
{
    sum = booking.Sum(t => t.Price);
}

ViewBag.AmountThisYear=sum;