我想将此代码转换为linq:
select t1.title, COUNT(*)as num
from t1 INNER join t2 on t2.gId = t1.Id
group by t1.title, t1.cId
having t1.cId = 2
我在下面尝试了以下代码:
from p in db.t1s join r in db.t2s on p.Id equals r.gId
where p.cId == 2
group p by p.title into g
select new{ name = from o in g select o.title, num = g.Count()}
但这不会正确返回COUNT。
请指导我如何解决问题
感谢
答案 0 :(得分:0)
如果没有样本数据,很难做到正确,但请尝试使用此代码段
from p in db.t1s
join r in db.t2s on p.Id equals r.gId
where p.cId == 2
group p by new {p.title, p.cId} into grouped
select new{ name = grouped.Key.title, num = grouped.Count()}
另外,请注意这个sql:
select t1.title, COUNT(*)as num
from t1 INNER join t2 on t2.gId = t1.Id
group by t1.title, t1.cId
having t1.cId = 2
由于COUNT(*),将始终返回1。原因是您已经过滤t1.cId = 2并将t1.cId分组为第二个参数。