I have post, vote and comment table. Each post can have N votes and N comments. I have been trying to find a way to do this query using Nhibernate HQL with no success.
SELECT P.Id, P.Title, P.TextDescription, ISNULL(V.TotalVotes,0), ISNULL(C.TotalComments, 0)
FROM
Post P
LEFT JOIN
(SELECT
PostId, count(PostId) as TotalVotes
FROM Vote
GROUP BY PostId) V
ON V.PostId = P.Id
LEFT JOIN
(SELECT
PostId, count(PostId) as TotalComments
FROM Comment
GROUP BY PostId) C
ON C.PostId = P.id
I pushed GROUP BY aggregations into nested SELECT statements because i want to group only PostId and not all those other columns. My Domain classes:
Post - properties:
int Id { get; set; }
string Title { get; set; }
string TextDescription { get; set; }
IList<Comment> Comments { get; set; } -> HasMany
IList<Vote> Votes { get; set; } -> HasMany
Comment - properties:
int Id { get; set; }
Post Post { get; set; } -> reference
Vote
int Id { get; set; }
Post Post { get; set; } -> reference
I'm really puzzled about this. I hope i'm not going in the wrong direction. Maybe i should just use the Nhibernate formula attribute in which i can declare an arbitrary SQL expression for my count's.
Any help would be very much appreciated..
Thanks!