Reputation: 171
I'm looking to create a Left outer join Nhibernate query with multiple on statements akin to this:
SELECT
*
FROM [Database].[dbo].[Posts] p
LEFT JOIN
[Database].[dbo].[PostInteractions] i
ON
p.PostId = i.PostID_TargetPost And i.UserID_ActingUser = 202
I've been fooling around with the critera and aliases, but I haven't had any luck figuring out how do to this. Any suggestions?
Upvotes: 5
Views: 8689
Reputation: 31
I spent a long while checking all kinds of posts that did not do what I needed and your post is the closest to what I was looking for.
From my tests (with nHibernate 3) your query is not correct. Actually your criteria looks more like this in SQL :
SELECT *
FROM [Posts] p
LEFT JOIN [PostInteractions] i
ON p.PostId = i.PostID_TargetPost
WHERE (i.UserID_ActingUser = 202 OR i.UserID_ActingUser IS NULL)
Which returns posts/interactions only when the interaction's ActingUser is 202 or that no interaction exists for the post.
After lot more tests I finally figured it out...
Try this (vb.net) :
session.CreateCriteria(Of Posts)("p") _
.CreateCriteria("Interactions", "i", _
NHibernate.SqlCommand.JoinType.LeftOuterJoin, _
Expression.Eq("i.ActingUser", user))
There's an overload to the CreateCriteria function using a "withClause". That worked perferctly for me and I believe that it's what you're looking for too.
I know the topic's pretty old but if it can help anyone else....
Also, for great examples on nHibernate queries (it was a huge help for me): http://ayende.com/blog/4023/nhibernate-queries-examples
Have fun!
Upvotes: 0
Reputation: 171
I actually figured it out. You need to do a check for null
.CreateCriteria("Interactions", "i", NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Add(Expression.Or(Expression.Eq("i.ActingUser", user), Expression.IsNull("i.ActingUser")))
this creates a left join on targetpost id and then eliminates all non null/non user interactions.
Upvotes: 12