Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当没有要求和的内容时,Linq.Sum()函数失败_C#_Linq - Fatal编程技术网

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

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”失败,因为

运行以下Linq查询时

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;