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

如何将Entity代码转为LINQ?解决‘value cannot be null’参数错误

错误原因及解决方案

核心错误点

  • search.MoTa赋值逻辑完全写反:原代码中if (search.MoTa != null) search.MoTa = "";,实际是把有值的查询条件清空,反而让search.MoTa为null的情况未处理,导致后续Contains方法传入null触发"value cannot be null"报错。
  • 未处理数据库字段的null值:若item.MoTa为null,直接调用Contains会抛出参数不能为空的异常;item.Ngay为null时直接访问Value会引发空引用异常。
  • 空集合求和未做安全处理:Sum在空集合场景下会返回null,赋值给decimal类型变量会引发错误。

修正后的完整代码

public ActionResult Search(SearchView search)
{
    IEnumerable<Transaction> thunhaps = null, chitieus = null;
    decimal totalTN = 0, totalCT = 0;
    int userid = Convert.ToInt32(Session["userid"]);
    var trans = new List<Transaction>();
    
    // 使用using自动释放数据库上下文资源
    using (var context = new QuanLyChiTieuDataContext())
    {
        // 修正:当search.MoTa为null时设为空字符串,保证查询条件合法
        if (search.MoTa == null)
            search.MoTa = "";

        if (search.TransType == "i" || search.TransType == "b")
        {
            thunhaps = from item in context.ThuNhaps
                       where item.UserID == userid
                             // 将null的MoTa转为空字符串后再判断包含关系
                             && (item.MoTa ?? "").Contains(search.MoTa)
                             // 过滤掉日期为null的记录,避免访问Value报错
                             && item.Ngay.HasValue 
                             && item.Ngay.Value >= search.TuNgay 
                             && item.Ngay.Value <= search.DenNgay
                       select new Transaction
                       {
                           Id = item.Inc_Id,
                           SoTien = (decimal)item.SoTien,
                           MoTa = item.MoTa ?? "", // 避免返回null给视图引发问题
                           GhiChu = item.GhiChu ?? "",
                           NgayGD = item.Ngay.Value,
                           TransType = "Income"
                       };

            // 空集合求和时返回0,避免null赋值给decimal
            totalTN = thunhaps.Sum(t => t.SoTien) ?? 0;
        }

        if (thunhaps != null)
            trans.AddRange(thunhaps);
    }

    ViewBag.Difference = totalTN - totalCT;
    return PartialView("SearchResult", trans);
}

关键修改说明

  1. 修正search.MoTa的空值处理逻辑,确保查询条件始终为合法字符串。
  2. 对数据库中可能为null的字段做安全转换,避免调用字符串方法或访问Nullable类型的Value时抛出异常。
  3. 给Sum结果添加空值合并运算符,保证空集合场景下求和结果为0,符合decimal类型的赋值要求。
  4. 使用using语句管理数据库上下文,自动释放资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Hiền Mai Vỗ Xuân

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:45:23