我想将简单的SQL查询转换为Linq到NHibernate:
SELECT NewsId
,sum(n.UserHits) as 'HitsNumber'
,sum(CASE WHEN n.UserHits > 0 THEN 1 ELSE 0 END) as 'VisitorsNumber'
FROM UserNews n
GROUP BY n.NewsId
我简化的UserNews类:
public class AktualnosciUzytkownik
{
public virtual int UserNewsId { get; set; }
public virtual int UserHits { get; set; }
public virtual User User { get; set; } // UserId key in db table
public virtual News News { get; set; } // NewsId key in db table
}
我写了以下linq查询:
var hitsPerNews = (from n in Session.Query<UserNews>()
group n by n.News.NewsId into g
select new { NewsId = g.Key, HitsNumber = g.Sum(x => x.UserHits),
VisitorsNumber = g.Count(x => x.UserHits > 0) }).ToList();
但是生成的sql只是忽略了我的x => x.UserHits > 0
语句,并且做了不必要的“左外连接”:
SELECT news1_.NewsId AS col_0_0_,
CAST(SUM(news0_.UserHits) AS INT) AS col_1_0_,
CAST(COUNT(*) AS INT) AS col_2_0_
FROM UserNews news0_
LEFT OUTER JOIN News news1_
ON news0_.NewsId=news1_.NewsId
GROUP BY news1_.NewsId
如何修复或解决此问题?也许这可以通过QueryOver语法更好地完成?
答案 0 :(得分:1)
我终于找到了问题的答案,我的解决方案基于对this question的回答:
我的QueryOver代码(我仍然不知道如何在Linq中对NHibernate执行此操作):
UserHitsDto adDtoAlias = null;
var userHits = Session.QueryOver<UserNews>()
.Select(Projections.Group<UserNews>(c => c.News.NewsId)
.WithAlias(() => adDtoAlias.NewsId),
Projections.Sum<UserNews>(x => x.UserHits)
.WithAlias(() => adDtoAlias.HitsNumber),
Projections.Sum(Projections.Conditional(
Restrictions.Where<UserNews>(f => f.UserHits > 0),
Projections.Constant(1),
Projections.Constant(0)
)).WithAlias(() => adDtoAlias.VisitorsNumber)
)
.TransformUsing(Transformers.AliasToBean<UserHitsDto>())
.List<UserHitsDto>();
它产生以下tsql:
SELECT this_.NewsId AS y0_,
SUM(this_.UserHits) AS y1_,
SUM((
CASE
WHEN this_.UserHits > @p0
THEN @p1
ELSE @p2
END)) AS y2_
FROM UserNews this_
GROUP BY this_.NewsId
其中@p0 = 0, @p1 = 1, @p2 = 0