我试图在NHibernate中复制这个SQL查询:
SELECT player.NAME,
Sum(achievement.value) AS 'Goals Scored'
FROM player
JOIN playerperformance
ON playerperformance.player_id = player.id
JOIN achievement
ON achievement.playerperformance_id = playerperformance.id
WHERE achievement.descriptor = 'Goals Scored'
GROUP BY player.NAME,
player.id
ORDER BY 'Goals Scored' DESC
这是我的NHibernate LINQ查询:
_dataAccessor.QueryOver<Player>()
.Inner.JoinQueryOver<PlayerPerformance>(player => player.Performances)
.Inner.JoinQueryOver<Achievement>(perf => perf.Achievements, () => achievementAlias)
.Where(a => a.Descriptor == "Goals Scored")
.SelectList(list => list.SelectGroup(player => player.Id).SelectSum(() => achievementAlias.Value))
.OrderBy(a => a.Value).Desc
.List()
;
这几乎是正确的。但OrderBy出错了。我不知道在OrderBy lambda中放什么会使它在SelectSum(...)
部分的别名上排序。生成的SQL中有一个别名:
SELECT this_.id AS y0_,
Sum(achievemen2_.value) AS y1_
FROM [player] this_
INNER JOIN [playerperformance] playerperf1_
ON this_.id = playerperf1_.player_id
INNER JOIN [achievement] achievemen2_
ON playerperf1_.id = achievemen2_.playerperformance_id
WHERE achievemen2_.descriptor = @p0
GROUP BY this_.id
ORDER BY achievemen2_.value DESC
所以我需要做的就是说服NHibernate做ORDER BY y1_
而不是ORDER BY achievemen2_.Value
。但我无法弄清楚如何获得总和的别名。
有什么想法吗?
答案 0 :(得分:0)
我明白了。 SelectSum(...)
有WithAlias
方法,因此我可以指向表示总和的整数别名。然后我只需使用OrderByAlias(...)
而不是OrderBy(...)
:
int sumAlias = 0;
_dataAccessor.QueryOver<Player>()
.Inner.JoinQueryOver<PlayerPerformance>(player => player.Performances)
.Inner.JoinQueryOver<Achievement>(perf => perf.Achievements, () => achievementAlias)
.Where(a => a.Descriptor == "Goals Scored")
.SelectList(list => list.SelectGroup(player => player.Id).SelectSum(() => achievementAlias.Value).WithAlias(() => sumAlias)
.OrderByAlias(() => sumAlias).Desc
.List<object[]>()
;