5

我有一个查询应该返回本周报告的总小时数。下面的代码返回正确的总小时数,但不是针对数据库中的特定用户。

    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;
        }

第一种方法返回数字 24,这是正确的,但正如我所说,不适用于特定用户。

我正在尝试这样做,但它给了我 0 作为回报。我究竟做错了什么?

    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;
        }
4

1 回答 1

2

更新- 故障排除方法,使用 u.Username 属性、字符串用户名和比较创建一个新的匿名类。将更容易可视化正在发生的事情

var users = (from u in context.Users
             select new
             { 
               UsernameDb = u.Username,
               UsernameSearch = username,
               Comparison = u.Username.Contains(username),
             }).ToList();

原来的

我会稍微修改您的查询:

  1. 使用join's 而不是from's withwhere子句
  2. 去除那个DefaultIfEmpty(0)

(1)更多的是为了可读性,但我认为(2)是你的问题的原因

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();

我还将确保以下查询返回结果。如果没有,那将是你的问题

var users = from u in context.Users
            where u.Username.Contains(username)
            select u;
于 2012-04-20T12:21:04.517 回答