Alex Rivera | Logout

NHibernate returning duplicate object in child collections when using Fetch

Asked 2011-01-17T14:32:50.953
16

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>();
Edit
Report

1 Answer

15

You can select single distinct results by specifying SetResultsTransformer(Transformers.DistinctRootEntity);

answered 2011-01-17T14:41:01.423

Your Answer