Reputation: 155
I am getting the data for the current month. For site.ID=4 there is no data in the backend. I am getting the column contains no data exception. How can I resolve this issue?
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
});
}
Upvotes: 0
Views: 3899
Reputation: 12324
Use DefaultIfEmpty after projecting the field you want to sum:
double manPowermonthly = context.ManHoursWorked
.Where(s => s.SiteID == site.ID && s.Date.Month==DateTime.Now.Month)
.Select(s => s.NumOfLabourForJOC)
.DefaultIfEmpty(0)
.Sum();
https://coding.abel.nu/2012/08/null-sematics-in-linqs-sum/
Upvotes: 4