[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 330
  • Last Modified:

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!
0
g_johnson
Asked:
g_johnson
  • 2
1 Solution
 
wdosanjosCommented:
I'm assuming this is LINQ2SQL.  In that case, you would get that error when i.emp_no == Emp.EmployeeId && i.work_date == dt returns no records.  Please try the following to work around this issue:
decimal? TotHrs2 = (from i in dc2.esna_JobAnalysis
		   where i.emp_no == Emp.EmployeeId &&
		   i.work_date == dt
		   select (decimal?)i.hours).Sum();

Open in new window


I hope this helps.
0
 
g_johnsonAuthor Commented:
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?
0
 
wdosanjosCommented:
Yes, that's correct.  I'm glad I was able to help.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now