NHibernate Left Outer Join

只愿长相守 提交于 2019-12-18 06:26:05

问题


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?


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/2756148/nhibernate-left-outer-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!