关联查询分组求和时单侧无数据的Decimal空值问题解决
订单未发货量计算的空值问题解决
定义的实体类
class Order { public long ID; public decimal ApprovedQuantity {get; set;} } class Shipment { public long OrderID {get; set;} public decimal SentAmount {get; set;} }
Order与Shipment是一对多关系,一个订单可拆分为多条发货记录,需编写查询计算订单的未发货量。
原查询代码及报错
最初编写的查询在数据库无对应发货记录时会抛出空值异常:
var items = from o in orders join shp in shipments on o.ID equals shp.OrderID into groupedShp let sentAmount = groupedShp.DefaultIfEmpty().Sum(shp => shp.SentAmount) select new { o.ID, NotSentAmount = o.ApprovedQuantity - Convert.ToDecimal(sentAmount) };
错误信息:
The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.
中文翻译:
无法将Null值分配给非Nullable类型System.Decimal的成员。
解决方法
将Sum方法修改为以下形式后问题解决:
let sentAmount = groupedShp.DefaultIfEmpty().Sum(shp => (decimal?)shp.SentAmount) ?? 0
原理说明
当订单无对应发货记录时,DefaultIfEmpty()会返回包含null的序列,直接对非可空的decimal类型求和会返回null,而null无法赋值给非可空decimal变量。将shp.SentAmount强制转换为可空decimal类型(decimal?),求和后会返回decimal?类型,再通过?? 0将null值替换为0,即可避免空值异常。
内容的提问来源于stack exchange,提问作者Mr. A
相关产品推荐
相关产品推荐

