Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query, messed up where clause in method

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;
        }
like image 445
rickard Avatar asked Nov 05 '22 01:11

rickard


1 Answers

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:

  1. Use join's instead of from's with where clauses
  2. Remove the DefaultIfEmpty(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;
like image 149
Aducci Avatar answered Nov 09 '22 14:11

Aducci