g_johnson
asked on
get a sum from a sql table using linq to sql visual studio 2008 c#
I am trying to sum a field in a table. If I use this method:
decimal? TotHrs2 = (from i in dc2.esna_JobAnalysis
where i.emp_no == Emp.EmployeeId &&
i.work_date == dt
select i.hours).Sum();
I get this error:
"The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type."
This, of course works:
var GetHours = from i in dc.esna_JobAnalysis
where i.emp_no == Emp.EmployeeId &&
i.work_date == dt
select new { i.hours };
decimal TotHrs1 = 0;
foreach (var GH in GetHours)
{
TotHrs1 += GH.hours;
}
However, I'm hoping to avoid the loop. Can't this be done with a .Sum using linq? What am I doing wrong in the first example?
Thank you!
decimal? TotHrs2 = (from i in dc2.esna_JobAnalysis
where i.emp_no == Emp.EmployeeId &&
i.work_date == dt
select i.hours).Sum();
I get this error:
"The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type."
This, of course works:
var GetHours = from i in dc.esna_JobAnalysis
where i.emp_no == Emp.EmployeeId &&
i.work_date == dt
select new { i.hours };
decimal TotHrs1 = 0;
foreach (var GH in GetHours)
{
TotHrs1 += GH.hours;
}
However, I'm hoping to avoid the loop. Can't this be done with a .Sum using linq? What am I doing wrong in the first example?
Thank you!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes, that's correct. I'm glad I was able to help.
ASKER