我在linq查询中遇到了一些麻烦,它通过返回来计算组。对于在MSSQL查询中返回0的结果,它返回1。 这是LINQ:
from qs in Ctx.QS
join qq in Ctx.QQ on qs.ID equals qq.QSID
join qt in Ctx.QT on qq.QTID equals qt.ID
join qv in Ctx.QV on qt.QID equals qv.QID
join qi in Ctx.QI on qs.ID equals qi.QSID
join r in Ctx.R on qi.ID equals r.QIID into r_1
from rr in r_1.DefaultIfEmpty()
where qv.ID == 1
group qs by new { qsId = qs.ID, qtId = qt.ID, qt.Title, qs.Name, qi.Group } into g
orderby g.Key.qsId
orderby g.Key.qtId
select new { g.Key.qsId, g.Key.qtId, g.Key.Title, g.Key.Name, g.Key.Group, Qty = g.Count() };
我正在尝试翻译此SQL查询:
SELECT qs.ID, qt.ID, qt.TITLE, qs.NAME, qi.GROUP, COUNT(r.ID)
FROM AVLQS qs
INNER JOIN AVLQQ qq ON qs.ID = qq.QSID
INNER JOIN AVLQT qt ON qq.AVLQTID = qt.ID
INNER JOIN AVLQV qv ON qt.AVLQID = qv.AVLQID
INNER JOIN AVLQI qi ON qs.ID = qi.AVLQSID
LEFT JOIN AVLR r ON qi.ID = r.AVLQIID
WHERE qv.ID = 1
GROUP BY qs.ID, qt.ID, qt.TITLE, qs.NAME, qi.GROUP
ORDER BY qt.ID, qs.ID
翻译几乎是100%,我看到的唯一区别是在Count()函数中,但我找不到在LINQ中做什么SQL在COUNT(r.ID)中做什么,因为在LINQ中谓词在Count()函数内接受期望“QS”而不是(R)。
我的情况比“复制”问题中的情况稍微复杂一点,因为在我的情况下,在Count()中期望的对象不知道它应该在Count内部检查的正确子对象( )。
答案 0 :(得分:3)
听起来你需要做两次修改来修复这个部分 - 另一个是修复排序。
如果您想查找左连接实际匹配的元素的数量(而不是"使用" DefaultIfEmpty
调用),您可能希望包含rr
in您的分组元素 - 然后在Count
调用中检查它是否为空。
你还想要更改你的orderby
条款,因为有两个orderby
条款并不意味着你不想要它:)我怀疑你想:
from qs in Ctx.QS
join qq in Ctx.QQ on qs.ID equals qq.QuestaoID
join qt in Ctx.QT on qq.QTID equals qt.ID
join qv in Ctx.QV on qt.QID equals qv.QID
join qi in Ctx.QI on qs.ID equals qi.QSID
join r in Ctx.R on qi.ID equals r.QIID into r_1
from rr in r_1.DefaultIfEmpty()
where qv.ID == 1
group new { qs, rr } by new { qsId = qs.ID, qtId = qt.ID, qt.Title, qs.Name, qi.Group } into g
orderby g.Key.qsId, g.Key.qtId
select new { g.Key.qsId, g.Key.qtId, g.Key.Title, g.Key.Name, g.Key.Group, Qty = g.Count(x => x.rr != null) };
或者,正如阿米特指出的那样,你可以只在小组中包含rr
:
from qs in Ctx.QS
join qq in Ctx.QQ on qs.ID equals qq.QuestaoID
join qt in Ctx.QT on qq.QTID equals qt.ID
join qv in Ctx.QV on qt.QID equals qv.QID
join qi in Ctx.QI on qs.ID equals qi.QSID
join r in Ctx.R on qi.ID equals r.QIID into r_1
from rr in r_1.DefaultIfEmpty()
where qv.ID == 1
group rr by new { qsId = qs.ID, qtId = qt.ID, qt.Title, qs.Name, qi.Group } into g
orderby g.Key.qsId, g.Key.qtId
select new { g.Key.qsId, g.Key.qtId, g.Key.Title, g.Key.Name, g.Key.Group, Qty = g.Count(rr => rr != null) };
答案 1 :(得分:2)
刚刚刺伤:
from qs in Ctx.QS
join qq in Ctx.QQ on qs.ID equals qq.QuestaoID
join qt in Ctx.QT on qq.QTID equals qt.ID
join qv in Ctx.QV on qt.QID equals qv.QID
join qi in Ctx.QI on qs.ID equals qi.QSID
join r in Ctx.R on qi.ID equals r.QIID into r_1
from rr in r_1.DefaultIfEmpty()
where qv.ID == 1
group rr by new { qsId = qs.ID, qtId = qt.ID, qt.Title, qs.Name, qi.Group } into g
orderby g.Key.qsId
orderby g.Key.qtId
select new { g.Key.qsId, g.Key.qtId, g.Key.Title, g.Key.Name, g.Key.Group, Qty = g.Count(x=>x!=null) };