当给这个函数一个id,在SQL中返回0行时,我得到以下错误:
无法将null值分配给System.Decimal类型的成员,该类型是非可空值类型。
修改查询以防止此问题的最佳方法是什么。我从一个不同于我在这里查询的表中提取值,所以我希望能够处理它给它一个“坏”的id。
public decimal GetSumOfValuesForAccount(Guid companyId)
{
return (from o in _context.Details
where o.CustomerID == companyId
select o).Sum(p => p.SomeValue.GetValueOrDefault());
}
返回错误:
答案 0 :(得分:4)
你应该能够返回:
return (from o in _context.Details
where o.CustomerID == companyId
select o).Sum(p => p.SomeValue) ?? -1.0;
或
decimal? temp = (from o in _context.Details
where o.CustomerID == companyId
select o).Sum(p => p.SomeValue);
return temp ?? -1.0;
??
运算符将检查null,如果为null,则返回下一个值。