NHibernate - using CreateMultiQuery

1.1k views Asked by At

My object model contains a Server entity which has collections of Adapter and Configuration objects.

I am trying to figure out how I can efficiently retrieve the details of a Server using a Multi Query as outlined in this article.

So far, based on the linked article, I have the following..

var query1 = "from Server s left outer join s.Adapters pa where s.ServerID = :serverID";
var query2 = "from Server s left outer join s.Configurations cc where s.ServerID = :serverID";

var result = Session.CreateMultiQuery()
                    .Add(Session.CreateQuery(query1))
                    .Add(Session.CreateQuery(query2))
                    .SetParameter("serverID", s.ServerID)
                    .List();

At this point result contains a list of 2-element lists. The first contains pairs of Server& Adapter objects while the second has pairs of Server& Connection objects.

My problem is that I have been unable to get from result to a single Server object with both lists populated.

1

There are 1 answers

2
amcdermott On BEST ANSWER

So I got this working - using Criteria rather than HQL. The solution was the following.

var criteria1 = DetachedCriteria.For<Server>()
                    .Add(Restrictions.Eq("ServerID", s.ServerID))
                    .SetFetchMode("Adapters", FetchMode.Eager)
                    .CreateCriteria("Adapters", JoinType.LeftOuterJoin);

var criteria2 = DetachedCriteria.For<Server>()
                    .Add(Restrictions.Eq("ServerID", s.ServerID))
                    .SetFetchMode("Configurations", FetchMode.Eager)
                    .CreateCriteria("Configurations", JoinType.LeftOuterJoin);

var result = Session.CreateMultiCriteria()
                    .Add(criteria1)
                    .Add(criteria2)
                    .List();

IList list = (IList)result[0];
var server = list[0] as Server;      

Not sure why this worked and the HQL didn't as, from a C# perspective, they seem to be doing exactly the same thing. Clearly something is quite different under the hood as the SQL generated by both approaches differ significantly.

I'd still prefer to use HQL as it seems more readable - but this will do for now.