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
var users = (from u in context.Users
select new
{
UsernameDb = u.Username,
UsernameSearch = username,
Comparison = u.Username.Contains(username),
}).ToList();
Original
I would modify your query slightly:
join
's instead of from
's with where
clausesDefaultIfEmpty(0)
(1) Is more for readability, but I think (2) is the cause of your problem
var totalTime = (from u in context.Users
join r in context.Reports on u.Id equals r.UserId
join w in context.Weeks on r.Id equals w.ReportId
join d in context.Days on w.DayId equals d.Id
where r.weekNr.Equals(currentWeek) && u.Username.Contains(username)
select d.Hour).Sum();
I would also make sure that the following query returns result. If not, than that would be your problem
var users = from u in context.Users
where u.Username.Contains(username)
select u;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With