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

问题描述 投票:0回答:2

我有这个代码

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,但这不起作用。如果不填写记录,我如何处理,以便我可以在此基础上做出决定?

c# asp.net-mvc entity-framework linq entity-framework-6
2个回答
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;
                    }

                }

0
投票

嗨发布问题,

要解决您的问题,您需要在尝试从中检索属性值之前检查结果是否为null。

你可以检查下面的代码没有什么魔法:

  1. 我压制了Try / Catch,因为没有兴趣去捕捉和重新抛出它。
  2. 我抑制了DefaultIfEmpty,因为string的默认值为null。
  3. 如果为null或者为null,我会为查询结果添加一个cheking。 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; }
© www.soinside.com 2019 - 2024. All rights reserved.