SUM()用法,C# ??用法,强制转换为Int类型错误

错误写法:

报错:到值类型“System.Int32”的强制转换失败,因为具体化值为 null。


var ccc = mesPend.Where(p => p.PendStartTime.Month == a && p.PendStartTime.Day <= d).
Select(p => (DbFunctions.DiffMinutes(p.PendStartTime, p.PendEndTime.Value) ?? 0));
 
var d = ccc.Sum();

转换为SQL语句

SELECT
CASE WHEN (DiffMinutes(`Extent1`.`PendStartTime`, `Extent1`.`PendEndTime`) IS NOT NULL)
 THEN (DiffMinutes(`Extent1`.`PendStartTime`, `Extent1`.`PendEndTime`))  ELSE (0) END AS `C1`
FROM `MesPend` AS `Extent1`
 WHERE (((`Extent1`.`PendEndTime` IS NOT NULL)
  AND (`Extent1`.`PendEndTime` >= @p__linq__0)) 
  AND (`Extent1`.`PendEndTime` < @p__linq__1))
   AND (((MONTH(`Extent1`.`PendStartTime`)) = @p__linq__2)
    AND ((DAY(`Extent1`.`PendStartTime`)) <= @p__linq__3))

可以看出上面SQL语句查询无数据的时候.
var d = ccc.Sum();
Sum() 返回值为null,强制转换为Int类型,会报如上错误

正确写法:


var ccc = mesPend.Where(p => p.PendStartTime.Month == a && p.PendStartTime.Day <= d).
Select(p => DbFunctions.DiffMinutes(p.PendStartTime, p.PendEndTime.Value));

var d = ccc..Sum() ?? 0;

你可能感兴趣的:(c#,java,开发语言)