The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

 CurrentStock = db.BillEntry.Where(b => b.GoodsId == item.GoodsId).Sum(b => (decimal?)b.Qty) ?? 0,

出现这种错误是因为没有获取到数据造成的,可以使用三元判断来操作,注意Sum里的Qty应该可以为空,如果为空则返回0,否则正式返回。

也可以用下面的方法: 

 CurrentStock = db.BillEntry.Where(b => b.GoodsId == item.GoodsId).Select(b => b.Qty).DefaultIfEmpty().Sum()

  

猜你喜欢

转载自www.cnblogs.com/firstcsharp/p/9968541.html