C# 当没有要求和的内容时,Linq.Sum()函数失败
运行以下Linq查询时C# 当没有要求和的内容时,Linq.Sum()函数失败,c#,linq,C#,Linq,运行以下Linq查询时 ViewBag.AmountThisYear = db.Bookings .Where(p => p.Id == id && p.StartDate.Year == DateTime.Now.Year) .Sum(t => t.Price); 当where子句中没有返回结果时,我得到以下错误 转换为值类型“System.Decimal”失败,因为
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Sum(t => t.Price);
当where子句中没有返回结果时,我得到以下错误
转换为值类型“System.Decimal”失败,因为
物化值为空。结果类型的泛型参数
或者查询必须使用可为空的类型
如何写入总和以应对这种情况因为没有返回行,所以不能求和。您可以使用
DefaultIfEmpty
:
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Select(t => t.Price)
.DefaultIfEmpty(0)
.Sum();
ViewBag.AMOUNTTHISEAR=总和 如果计算字段不可为空,则需要先强制转换为可为空进行计算。因此,变化如下所示:
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Sum(t => (decimal?)t.Price) ?? 0m;
另外,添加合并运算符(??)将null转换为0。什么是
Price
?id
字段的类型是什么?.Where(t=>t.Price.HasValue).Sum(t=>t.Price);Price是一个十进制数(不可为null),Id也是一个intWorks,但需要执行两次查询。
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Sum(t => (decimal?)t.Price) ?? 0m;