【问题标题】:How to solve the cast to value type 'System.Decimal' failure error如何解决强制转换为值类型“System.Decimal”失败错误
【发布时间】:2015-06-03 00:21:56
【问题描述】:
转换为值类型“System.Decimal”失败,因为具体化值为 null。结果类型的泛型参数或查询必须使用可为空的类型。
public class Bar
{
[Key]
public int BarID { get; set; }
public int Quantity { get; set; }
public decimal? UnitTotal{get { return Quantity * (Pricelist == null ? 0 : Pricelist.Price); }}
public decimal? DailyTotal { get; set; }
public int PricelistID { get; set; }
public virtual Pricelist Pricelist { get; set; }
}
bar.DailyTotal = db.Bars.Sum(h => h.Quantity * h.Pricelist.Price);
【问题讨论】:
标签:
c#
linq
asp.net-mvc-5
【解决方案1】:
编辑:
听起来其中一种映射类型正在解析为 null。例如数量或价格字段。
检查架构/映射以确保如果它们可以为空,则它们被映射为可以为空的类型。
【解决方案2】:
要查看问题出在哪里,请尝试使用 foreach 而不是那个 lambda 表达式。
decimal sum = 0;
foreach (var item in db.Bars)
{
if (item.Pricelist != null && item.Pricelist.Price != null)
{
sum += item.Quantity * item.Pricelist.Price;
}
else
{
//Check this specific item from db.Bars which may have an inconsistent state
}
}
Quantity 是一个不可为空的 int,所以基本上我不认为它是问题所在。因此,Pricelist 可能是原因或其 Price 属性,这似乎是一个可以为空的小数。
当然,您也可以调试 lambda 表达式,但在我看来,有时详细的 foreach 会更清晰。
【解决方案3】:
如果计算字段不可为空,则需要先强制转换为空进行计算。所以变化如下:
bar.DailyTotal = db.Bars.Sum(h => (decimal?) h.Quantity * h.Pricelist.Price) ?? 0m;
另外,添加合并运算符 (??) 将 null 转换为 0。