错误写法:
报错:到值类型“System.Int32”的强制转换失败,因为具体化值为 null。
int a = mesPend.Where(p => p.PendStartTime.Month == a && p.PendStartTime.Day <= d).
Select(p => DbFunctions.DiffSeconds(p.PendStartTime, p.PendEndTime.Value)??0/ 60).Sum();
转换为SQL语句
SELECT
CASE WHEN (DiffSeconds(`Extent1`.`PendStartTime`, `Extent1`.`PendEndTime`) IS NOT NULL)
THEN (DiffSeconds(`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语句查询无数据的时候.Sum() 返回值为null,强制转换为Int类型,会报如上错误
正确写法:
int a = mesPend.Where(p => p.PendStartTime.Month == a && p.PendStartTime.Day <= d).
Select(p => DbFunctions.DiffSeconds(p.PendStartTime, p.PendEndTime.Value)/ 60).Sum() ?? 0