P Sriharsha
P Sriharsha

Reputation: 155

Column contains null data in asp.net mvc

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

Answers (1)

Steve Greene
Steve Greene

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

Related Questions