遇到Group by和加入EF c时遇到问题

时间:2018-06-19 01:07:51

标签: c# entity-framework

我无法将此T-SQL代码转换为EF C#

select 
    se.pcname, count(u.usrid) as total 
from 
    tbusers as u
inner join 
    tbhcontainer as hc on u.hcid = hc.hcid
inner join 
    tbusersettings as se on hc.sid = se.sid
where 
    day(u.created) = 18
group by  
    se.pcname
order by 
    total desc

tbusers:

Username, PCName, Usrid, Created, HCID

tbhcontainer:

hcid, sid

tbusersettings:

sid, pcname

编辑1:

DateTime yesterday = DateTime.UtcNow.Date.AddDays(-1).AddHours(-3);
DB_121002_psmainEntities ctx = new DB_121002_psmainEntities();

var res = from r in ctx.tbusers
          join hc in ctx.tbhcontainers on r.hcid equals hc.hcid
          join s in ctx.tbUserSettings on hc.sid equals s.sid
          group s by s.pcname
          where r.created >= yesterday || r.created <= DateTime.Today
          select r;
          return res.Count();

它在所有级别都失败了,只是不知道如何使用group by with joined tables

1 个答案:

答案 0 :(得分:1)

直接翻译看起来更像是这样:

from u in ctx.Users
join hc in ctx.HContainers on u.Hcid equals hc.Hcid
join us in ctx.UserSettings on hc.Sid equals us.Sid
where u.Created.Day == 18
group u.Userid by us.Pcname into g
let total = g.Count()
orderby total descending
select new
{
    pcname = g.Key,
    total,
}

如果在分组后有其他子句,则需要将结果放入另一个变量(g)。然后,您可以访问组密钥并在该组上执行任何聚合功能。

相关问题