Conditional row count in linq to nhibernate doesn't work
Posted
by
Lucasus
on Stack Overflow
See other posts from Stack Overflow
or by Lucasus
Published on 2012-03-29T11:27:35Z
Indexed on
2012/03/29
11:29 UTC
Read the original article
Hit count: 228
I want to translate following simple sql query into Linq to 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
My simplified UserNews class:
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
}
I've written following linq query:
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();
But generated sql just ignores my x => x.UserHits > 0
statement and makes unnecessary 'left outer join':
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
How Can I fix or workaround this issue? Maybe this can be done better with QueryOver syntax?
© Stack Overflow or respective owner