Link to home
Start Free TrialLog in
Avatar of g_johnson
g_johnsonFlag for United States of America

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!
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of g_johnson

ASKER

Thank you, that worked.  If I understand what you did, we are telling linq that if there are no records, return the resulting null as a nullable decimal so that it matches our declaration.  Is that about right?
Yes, that's correct.  I'm glad I was able to help.