我正在获取当月的数据。对于site.ID = 4,后端没有数据。我得到的列包含没有数据异常。我该如何解决这个问题?
List<ManHourReport> manHoursReports = new List<ManHourReport>();
var sites = context.JocSites.Where(j => j.JOCid == jocID).ToList();
foreach (var site in sites)
{
double manPowermonthly = context.ManHoursWorked.
Where(s => s.SiteID == site.ID && s.Date.Month==DateTime.Now.Month).
Sum(m => m.NumOfLabourForJOC); // here for the site.ID=4, there is no data in the backend. I am getting the error.
double manHoursMonthly = context.ManHoursWorked.
Where(s => s.SiteID == site.ID && s.Date.Month == DateTime.Now.Month).
Sum(m => m.NumOfWorkingHoursJOC);
double manHoursYearly = context.ManHoursWorked.
Where(s => s.SiteID == site.ID && s.Date.Year == DateTime.Now.Year).
Sum(m => m.NumOfWorkingHoursJOC);
manHoursReports.Add(new ManHourReport()
{
SiteManPower = manPowermonthly,
SiteManHourMonthly = manHoursMonthly,
SiteManHourYearly = manHoursYearly
});
}
答案 0 :(得分:3)
在投影您想要求和的字段后使用DefaultIfEmpty:
double manPowermonthly = context.ManHoursWorked
.Where(s => s.SiteID == site.ID && s.Date.Month==DateTime.Now.Month)
.Select(s => s.NumOfLabourForJOC)
.DefaultIfEmpty(0)
.Sum();