0

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
                });
    }
1
  • You should check if context.ManHoursWorked.Where(...) return any value before trying to SUM values. Commented Jan 15, 2016 at 14:04

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.