如果linq查询找不到匹配的记录,则对象引用未设置错误?

时间:2019-04-14 12:08:23

标签: c# asp.net-mvc entity-framework linq entity-framework-6

我有这个代码

public object GetMaxReportNo(string OfficeStationCombination = "")
        {
            try
            {
                InspectionReport InspectionReport = new InspectionReport();
                string VelosiReportNo = "";

                var query = uow.InspectionReportRepository.GetQueryable().AsQueryable();

                if (query.Any())
                {
                    VelosiReportNo = query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination)).OrderByDescending(x => x.InspectionReportID).DefaultIfEmpty(null).FirstOrDefault().VelosiReportNo;
                }

                return VelosiReportNo;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

此行:

VelosiReportNo = query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination)).OrderByDescending(x => x.InspectionReportID).DefaultIfEmpty(null).FirstOrDefault().VelosiReportNo;

抛出错误:

对象引用未设置为对象的实例。

当我传递数据库中尚不存在记录的参数时。但是,我不知道它返回了什么?我该如何控制?

我已经处理过null,但是没有用。如果不修改记录该如何处理,以便我可以据此做出决定?

2 个答案:

答案 0 :(得分:0)

query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination)).Any()

成功了!

完整代码;

                if (query.Any())
                {
                    if (query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination)).Any())
                    {
                        VelosiReportNo = query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination)).OrderByDescending(x => x.InspectionReportID).FirstOrDefault().VelosiReportNo;
                    }
                    else
                    {
                        VelosiReportNo = null;
                    }

                }

答案 1 :(得分:0)

您好发帖问题,

要解决您的问题,您需要先检查结果是否不为null,然后再尝试从中检索属性值。

您可以检查下面没有任何魔术的代码:

  1. 我禁止“尝试/捕获”,因为没有兴趣捕获并重新扔掉它。
  2. 我禁止DefaultIfEmpty,因为字符串的默认值为null。
  3. 如果不为null,我会添加一个查询结果。

    public object GetMaxReportNo(string OfficeStationCombination = "")
    {
            InspectionReport InspectionReport = new InspectionReport();
            string VelosiReportNo = "";
    
            var query = uow.InspectionReportRepository.GetQueryable().AsQueryable();
    
            if (query.Any())
            {
                var queryResult = query.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination))
                                      .OrderByDescending(x => x.InspectionReportID)
                                      .FirstOrDefault();
                if (queryResult != null)
                    VelosiReportNo = queryResult.VelosiReportNo;
            }
    
            return VelosiReportNo;
    }