I already found this request. SQL returns the result that I want, but I cannot figure out how to express a query in HQL.
Here's the SQL :
select thread.ThreadId,
thread.Title,
thread.CreatedOn,
thread.ViewCount,
thread.CreatedBy,
thread.ForumId
from Threads thread
where
(thread.ThreadId in(select post.ThreadId from Posts post
where (post.CreatedBy=2 )))
AND
(2!=(select TOP 1 post2.CreatedBy from Posts post2
where (post2.ThreadId=thread.ThreadId ) ORDER BY post2.CreatedOn DESC))
I think I need to use DetachedCriteria to create a correlated subquery, but I'm having real problems.
Here where I am :
DetachedCriteria latestPostInThread = DetachedCriteria.For(typeof (ForumPost),
"post2")
.Add(Expression.EqProperty("post2.ThreadId", "post.ThreadId"))
.AddOrder(Order.Desc("CreatedOn"))
.SetFirstResult(0)
.SetMaxResults(1);
and for the main request :
ICriteria critMain = CreateCriteria(typeof (ForumPost), "post")
.Add(Expression.Eq("CreatedBy",user.ID))
.Add(Subqueries.Ne("CreatedBy", latestPostInThread));
This is clearly wrong - I need to get userId from lastPostInThread in order to use it as my subquery, but I'm completely incapable.
Any help would be greatly appreciated! I hate going back to SQL for something that I'm sure of nHibernate is not so difficult to achieve.
source
share