Desired loading of child and child collections in NHibernate

I have a problem with NHibernate trying to load a small data hierarchy. My domain model looks like this:

class GrandParent { int ID{get;set;} IList<Parent> Parents {get; set;} } class Parent { IList<Child> Children {get; set;} } class Child { } 

and I would love to download all parents and children for this GrandParent. This Linq-to-NH query creates the correct SQL and loads GrandParent, as expected: (the example assumes that the grandparents have 2 parents, each of which has 2 children - only 4 children).

 var linq = session.Linq<GrandParent>(); linq.Expand("Parents"); linq.Expand("Parents.Children"); linq.QueryOptions.RegisterCustomAction(c => c.SetResultTransformer(new DistinctRootEntityResultTransformer())); var grandparent = (select g from session.Linq<GrandParent>() where g.ID == 1 select g).ToList(); Assert(grandparent.Count == 1); //Works Assert(grandparent.Parents.Count == 2); //Fails - count = 4! 

The grandparent.Parents collection contains 4 elements, 2 of which are duplicates. It seems that DistinctRootEntityResultTransformer only works with collections at level 1, so the collection of parents is duplicated depending on how many children each parent has.

Is it possible to force NH to include only individual parent objects?

Many thanks.

+4
c # nhibernate eager-loading linq-to-nhibernate
source share
1 answer

If your mapping is set to FetchType.Join, try changing it to FetchType.Select.

+1
source share

All Articles