I have a parent child relationship where I want to return only one parent and load all the children. I am using criteria because it is a dynamic query.
var messageQueueId = this.GetPropertyName<MessageQueue>(x => x.Id);
var query = _sessionManager.Session.CreateCriteria<MessageQueue>(QUEUE_ALIAS);
query.SetFirstResult(_pageOffset);
query.SetMaxResults(_pageSize);
query.Add(Restrictions.In(messageQueueId, _messageQueueIds));
query.List<MessageQueue>();
This returns the parent (MessageQueue) but not it's children (SearchMatches).
When I try to do this:
var query = _sessionManager.Session
.CreateCriteria<MessageQueue>(QUEUE_ALIAS)
.CreateAlias(this.GetPropertyName<MessageQueue>(x => x.SearchMatches)
, MATCH_ALIAS, JoinType.LeftOuterJoin);
Then I get the children loaded, but also I receive duplicate parents. I understand why this is happening. However I don't understand how to get the first scenario to just load the SearchMatches automatically?
Here are my entitites:
public class MessageQueue : EntityBase
{
...
public virtual IList<SearchMatch> SearchMatches { get; set; }
...
}
public class SearchMatch : EntityBase
{
...
public virtual MessageQueue MessageQueue { get; set; }
...
}
Fluent NHibernate is set to DefaultCascade.All()
. I have no other overrides for these objects.
I have tried to use Inverse()
and Not.LazyLoad()
off of the MessageQueue override. Also Tried to EagerLoad off the CreateAlias. But I am still not getting what I need back.
I would suggest to use the
batch-size=""
setting. It will end up in1) one query issued by us (
query.List<MessageQueue>();
),2) NHibernate will use then one (or just few) query/ies to load collection for each returned
MessageQueue
.19.1.5. Using batch fetching
The fluent alternative is (both collection and class level)
Also check: