Search code examples
c#nhibernatequeryover

Filtering Sub Collections with QueryOver


I would like to write a query that filters a child collection of the base type in my QueryOver. For example...

class Person{
    List<Contact> contacts;
}

class Contact{
    string PhoneNumber;
    bool isHome;
}

Then

QueryOver.Of<Person>()
 .JoinQueryOver(p => p.Contact)
 .Where(c => c.isHome);

Which I want to return all the people and have each ones Contacts collection only populated with the contacts that isHome is true.

I have tried Transformers to try and get the correct result. The DistinctRootEntity transformer does not keep the expected filter on the child collection. AliasToEntityMap returns the correct rows but the result is returned as a Dictionary not the Root type.

I am trying to replace the usage of an NHibernate filter. I'm not sure if this is possible.


Solution

  • Almost immediately after posting this I found the answer to my question. To achieve what I was attempting to get all that is required is to specify the JoinType and a Transformer.

    QueryOver.Of<Person>()
     .JoinQueryOver(p => p.Contact, JoinType.LeftOuterJoin)
     .Where(c => c.isHome) 
     .TransformUsing(Transformers.DistinctRootEntity);
    

    Now I get all the people with just their home contacts