Tuesday, January 8, 2013

NHibernate: Get distinct results when using the QueryOver API

In a project we had the following NHibernate query code:
var decisions= session.QueryOver<Decisions>()
       .Where(a => a.Idproject == this.Id)
       .Fetch(a => a.DecisionMakers)
       .Eager
          .List()

What’s important here is the Fetch() statement. The Fetch().Eager statement will not only load the Decisions but also the related Decision Makers when we execute this query(probably by using a join).

The problem was that when a decision has more then one decisionmaker, we get the same decision back multiple times(one time for each decision maker that was found).

To solve this, you have to tell NHibernate to filter the results by calling .TransformUsing(Transformers.DistinctRootEntity).

No comments: