You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理Sum()方法中TimeSpan出现的“可空值类型可能为null”警告

解决方案

修正后代码

return result.Include(e => e.Episodes)
    // 数据库层面完成排序分页,避免全量数据加载到内存
    .OrderByDescending(c => c.CoursePrice)
    .Skip(skip)
    .Take(take)
    .AsEnumerable()
    .Select(c => new ShowListCoursesViewModel()
    {
        CourseId = c.CourseId,
        CourseImageName = c.CourseImageName,
        CoursePrice = Convert.ToDecimal(c.CoursePrice),
        CourseTitle = c.CourseTitle,
        CourseTotalTime = new TimeSpan(c.Episodes.Sum(t => (t.EpisodeTimeLength ?? TimeSpan.Zero).Ticks))
    }).ToList();

说明

  • 核心修改使用??空合并运算符处理可空TimeSpan的null场景:当t.EpisodeTimeLength为null时,自动取值为TimeSpan.Zero(即00:00:00)参与求和计算,完全匹配要求的null值视为0的规则,示例输入[null, 01:00:00, 01:00:00]会得到02:00:00的输出结果
  • 不再直接访问可空类型的.Value属性,编译器的「Nullable value type may be null」警告会自动消除
  • 调整了排序、分页的执行顺序:原代码在AsEnumerable()之后执行分页会先把所有符合条件的课程数据加载到内存再处理,调整到AsEnumerable()之前执行后,EF Core会生成对应的SQL语句在数据库层面完成排序和分页,大数据量下性能提升明显
  • 原代码中CopurseTitle为拼写错误,可根据实际属性名做对应修正

内容的提问来源于stack exchange,提问作者Hossein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:24:03