Search code examples
nhibernatefluent-nhibernatedto

Return only the Parent using nHibernate


Im pretty new to nhibernate so this may be quite straightforward but i havent found an answer on the web yet.

Lets say i have a Parent class and a Child class. The Parent Class can have many Child classes associated with it. Now when i try to load a specific Parent nhibernate also populates its Child collection for me. There are situations where I want to just return a Parent class without a Child collection.

I know i can turn on Lazy loading but that wont work as im serializing the Parent to XML. The XML serialiser cannot work with the nhibernate PersistanceBag that contains the Child collection.

So is there a way to define a Parent class, lets say ParentView which works on the same table but only contains the Parent properties and not all its children and grandchildren?


Solution

  • Define a class ParentView that contains the columns you need to retrieve. Make sure this class has one parameterless constructor.

    ISession session = NHibernateHelper.Session;
    ISQLQuery query = session.CreateSQLQuery("select Parent_ID, Name form Parent where Parent_ID = :parentID");
    query.SetInt32("parentID", parentID);
    IList<ParentView> parentView = query.SetResultTransformer(Transformers.AliasToBean<ParentView>()).List<ParentView>();
    return parentView;