NHibernate returning duplicate object in child collections when using Fetch

Posted by UpTheCreek on Stack Overflow See other posts from Stack Overflow or by UpTheCreek
Published on 2011-01-17T14:32:50Z Indexed on 2011/01/18 1:53 UTC
Read the original article Hit count: 498

Filed under:

When doing a query like this (using Nhibernate 2.1.2):

 ICriteria criteria = session.CreateCriteria<MyRootType>()
                .SetFetchMode("ChildCollection1", FetchMode.Eager)
                .SetFetchMode("ChildCollection2", FetchMode.Eager)
                .Add(Restrictions.IdEq(id));

I am getting multiple duplicate objects in some cartesian fashion. E.g. if ChildCollection1 has 3 elements, and ChildColection2 has 2 elements then I get results with each element in ChildColection1 one duplicated, and each element in ChildColection2 triplicated! This was a bit of a WTF moment for me...

So how to do this correctly?

  • Is using SetFetchMode like this only supported when specifying one collection?
  • Am I just using it wrong (I've seen some references to results transformers, but imagined this would be simplier).
  • Is this something that's different in NH3?

Update:

As per Felice's suggestion, I tried using the DistinctRootEntity transformer, but this is still returning duplicates. Code:

ICriteria criteria = session.CreateCriteria<MyRootType>()
                .SetFetchMode("ChildCollection1", FetchMode.Eager)
                .SetFetchMode("ChildCollection2", FetchMode.Eager)
                .Add(Restrictions.IdEq(id));

 criteria.SetResultTransformer(Transformers.DistinctRootEntity);

 return criteria.UniqueResult<MyRootType>();

© Stack Overflow or respective owner

Related posts about nhibernate