I have a query that should return a sum of total hours reported for the current week.
This code below returns the Correct total of hours but not for a specific user in the database.
public int reportedWeekTime(int currentWeek, string username)
{
var totalTime = (from u in context.Users
from r in context.Reports
from w in context.Weeks
from d in context.Days
where u.Id == r.UserId && r.weekNr.Equals(currentWeek) && r.Id == w.ReportId && w.DayId == d.Id
select d.Hour).DefaultIfEmpty(0).Sum();
return totalTime;
}
The first method returns the number 24, wich is correct but as i said, not for a specific user.
I am trying to do this, but it gives me 0 in return. What am i doing wrong?
public int reportedWeekTime(int currentWeek, string username)
{
var totalTime = (from u in context.Users
from r in context.Reports
from w in context.Weeks
from d in context.Days
where u.Id == r.UserId && r.weekNr.Equals(currentWeek) && r.Id == w.ReportId && w.DayId == d.Id && u.Username.Contains(username)
select d.Hour).DefaultIfEmpty(0).Sum();
return totalTime;
}
Update – Troubleshooting approach, create a new anonymous class with the u.Username property, the string username, and the comparison. It will be easier to visualize what is going on
Original
I would modify your query slightly:
join‘s instead offrom‘s withwhereclausesDefaultIfEmpty(0)(1) Is more for readability, but I think (2) is the cause of your problem
I would also make sure that the following query returns result. If not, than that would be your problem