ric*_*ard 5 c# silverlight linq-to-entities entity-framework windows-phone-7
我有一个查询,应该返回当前报告的总小时数.下面的代码返回正确的小时总数,但不是数据库中特定用户的小时数.
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;
}
Run Code Online (Sandbox Code Playgroud)
第一种方法返回数字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;
}
Run Code Online (Sandbox Code Playgroud)
更新- 故障排除方法,使用 u.Username 属性、字符串用户名和比较创建一个新的匿名类。更容易想象正在发生的事情
var users = (from u in context.Users
select new
{
UsernameDb = u.Username,
UsernameSearch = username,
Comparison = u.Username.Contains(username),
}).ToList();
Run Code Online (Sandbox Code Playgroud)
原来的
我会稍微修改你的查询:
join's 代替from'swhereDefaultIfEmpty(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();
Run Code Online (Sandbox Code Playgroud)
我还要确保以下查询返回结果。如果没有,那就是你的问题
var users = from u in context.Users
where u.Username.Contains(username)
select u;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
336 次 |
| 最近记录: |