Linq 表达式Sum 抛出“不能将 Null 值赋给类型为 System.Decimal (不可为 null 的值类型)的成员”的最佳解决方法

时间:2022-06-02 20:51:53
昨天Linq 使用Sum 表达式抛出了“不能将 Null 值赋给类型为 System.Decimal (不可为 null 的值类型)的成员”
 
var val = dc.DailyData.Where(x => x.ValueTime == DateTime.Now).Sum(x => x.TodayPower);

检查了一下生成的SQL语句,结果如下:


{SELECT SUM([t0].[TodayPower]) AS [value]
FROM [dbo].[DailyData] AS [t0]
WHERE [t0].[ValueTime] = @p0
-- @p0: Input DateTime (Size = 0; Prec = 0; Scale = 0) [2012/3/29 0:00:00]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.5420


}


Google了一下,有一个有人提出了强转http://www.cnblogs.com/mine/archive/2009/02/27/1399770.html
于是代码改成如下:
var val = dc.DailyData.Where(x => x.ValueTime == DateTime.Now).Sum(x => (decimal?)x.TodayPower);

不过再检查了生成的SQL语句发现生成的查询语句变成了如下:


{SELECT SUM([t1].[value]) AS [value]
FROM (
    SELECT [t0].[TodayPower] AS [value], [t0].[ValueTime]
    FROM [dbo].[DailyData] AS [t0]
    ) AS [t1]
WHERE [t1].[ValueTime] = @p0
-- @p0: Input DateTime (Size = 0; Prec = 0; Scale = 0) [2012/3/29 17:31:18]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.5420


}


查了一下MSDN,对于SUM函数重载的说明都基本相同,没有特别之处。最后我尝试了一下使用 as运算符,居然有惊人的发现,生成了最优的SQL语句了。
var val = dc.DailyData.Where(x => x.ValueTime == DateTime.Now).Sum(x =>x.TodayPower as decimal?);

生成的SQL语句如下:
{SELECT SUM([t0].[TodayPower]) AS [value]
FROM [dbo].[DailyData] AS [t0]
WHERE [t0].[ValueTime] = @p0
-- @p0: Input DateTime (Size = 0; Prec = 0; Scale = 0) [2012/3/29 17:47:04]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.5420


}