下面显示抛出运行时错误。虽然编译得很好:
float? totalSum = (from t in _context.Orders
join c in _context.Customers.Where(c => c.region=="NW")
on t.CustomerId equals c.CustomerId
select t.price).Sum();
错误:
Unable to cast object of type 'System.Double' to type 'System.Nullable`1[System.Single]'.
但是以下工作(唯一的区别是我在应用ToList()
之前使用.Sum()
- 但根据definition of Sum()它应该可以在不使用ToList()
的情况下工作 - 正确?
float? totalSum = (from t in _context.Orders
join c in _context.Customers.Where(c => c.region=="NW")
on t.CustomerId equals c.CustomerId
select t.price).ToList().Sum();
更新:
price
属性的数据类型为float?
,映射到SQL Server 2012中的数据类型real
。
答案 0 :(得分:0)
选择t.price
可能会产生null,您收到的错误消息会反映出来。检查null:
选择t.price ?? 0.0F
或去.ToList(); 您也可以实现自己的Sum()来检查null。