我有这个代码
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
,但这不起作用。如果不填写记录,我如何处理,以便我可以在此基础上做出决定?
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;
}
}
嗨发布问题,
要解决您的问题,您需要在尝试从中检索属性值之前检查结果是否为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;
}