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

API方法出现Object Reference未实例化异常及数据查询失败问题

解决API筛选逻辑中的空引用异常问题

问题根源

出现Object Reference not set to an instance of an object空引用异常,核心原因是:

  • 某条Produtos数据的Nome字段为null,调用Contains方法时触发空引用
  • 传入的term参数为null,调用Contains方法时触发空引用
    调试时停在name为"kn"的条目,大概率是该条数据的Nome实际为null。

修复方案

方案1:ORM查询阶段筛选(推荐,性能更优)

如果_repository.GetAllProducts()返回的是IQueryable(比如Entity Framework),将筛选逻辑放在分页前,让数据库直接返回符合条件的数据,同时添加空值防护:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
{
    // 处理term为null的情况,转为空字符串
    var searchTerm = term ?? string.Empty;
    
    var productsQuery = _repository.GetAllProducts();
    
    // 仅当搜索词非空时添加筛选条件,同时排除Nome为null的数据
    if (!string.IsNullOrEmpty(searchTerm))
    {
        productsQuery = productsQuery.Where(p => p.Nome != null && p.Nome.Contains(searchTerm));
    }
    
    // 执行分页并转为列表
    var produtos = productsQuery.Skip((page - 1) * pageSize).Take(pageSize).ToList();
    
    if (!produtos.Any())
    {
        // 抛出更具体的异常,便于调用方处理
        throw new KeyNotFoundException("未找到匹配的产品");
    }

    return produtos;
}

方案2:内存中筛选(适用于已加载到内存的集合)

如果必须先分页再在内存筛选,修改原代码的空值检查逻辑:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
{
    var products = _repository.GetAllProducts().Skip((page - 1) * pageSize).Take(pageSize).ToList();

    List<Produtos> produtos = new List<Produtos>();

    products.ForEach(produto =>
    {
        Console.WriteLine(produto);
        // 先检查Nome和term都不为null,再执行匹配
        if (!string.IsNullOrEmpty(produto.Nome) && !string.IsNullOrEmpty(term) && produto.Nome.Contains(term))
        {
            Console.WriteLine("if statement");
            produtos.Add(produto);
        }
    });
    
    if (!produtos.Any())
    {
        throw new KeyNotFoundException("未找到匹配的产品");
    }

    return produtos;
}

关键修复点

  • 空值防护:添加string.IsNullOrEmpty检查,避免对null值调用Contains方法
  • 查询优化:优先在数据库层面完成筛选,减少内存处理的数据量
  • 异常规范:使用具体异常类型替代通用Exception,提升错误处理的可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:10:20