【发布时间】:2019-04-14 12:08:22
【问题描述】:
我有这个代码
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