强制转换为值类型“System.Double”失败的原因

本篇内容主要讲解“强制转换为值类型“System.Double”失败的原因”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“强制转换为值类型“System.Double”失败的原因”吧!

  foreach (var item in entityList)
                {
                    ChannelReportDto channelReportDto = new ChannelReportDto();
                    channelReportDto.Id = item.Id;
                    channelReportDto.YueziCenterId = item.YueziCenterId;
                    channelReportDto.YueziCenterName = item.YueziCenterName;
                    channelReportDto.ChannelName = item.ChannelName;
                    channelReportDto.SumProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsDeleted == false).Select(s => s.SumProfitAmount).Sum(); 
                    channelReportDto.SettleProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsSettlement == true).Select(s => s.SumProfitAmount).Sum();
                    channelReportDto.NoSettleProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsSettlement == false).Select(s => s.SumProfitAmount).Sum();
                    list.Add(channelReportDto);

                }

这样写的时候 就报了这个错 The cast to value type 'System.Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

主要原因是没有适合查询条件的行 去计算,

所以改成以下写法就OK

 foreach (var item in entityList)
                {
                    ChannelReportDto channelReportDto = new ChannelReportDto();
                    channelReportDto.Id = item.Id;
                    channelReportDto.YueziCenterId = item.YueziCenterId;
                    channelReportDto.YueziCenterName = item.YueziCenterName;
                    channelReportDto.ChannelName = item.ChannelName;
                    channelReportDto.SumProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsDeleted == false).Sum(s =>(double?)s.SumProfitAmount)??0.00; 
                    channelReportDto.SettleProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsSettlement == true).Sum(s => (double?)s.SumProfitAmount) ?? 0.00;
                    channelReportDto.NoSettleProfitAmount = OrderServiceProjectresult.Where(w => w.ChannelId == item.Id && w.IsSettlement == false).Sum(s => (double?)s.SumProfitAmount) ?? 0.00;
                    list.Add(channelReportDto);

                }

到此,相信大家对“强制转换为值类型“System.Double”失败的原因”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!