NHibernate Left Outer Join
Asked Answered
C

2

5

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?

Clupeoid answered 3/5, 2010 at 4:43 Comment(0)
C
12

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.

Clupeoid answered 3/5, 2010 at 4:58 Comment(0)
B
0

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!

Bibber answered 19/2, 2015 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.