Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate and Collection Counts

Tags:

c#

nhibernate

I have the following class setup for persistence using NHibernate

public class Person
{
    public string Name { get; set; }
    public IList<Person> Subordinates { get; set; }
}

Now say I have a grid with two columns, "Name" and "Number of Subordinates" what is the best way of doing this in NHibernate whilst retaining the use of domain objects where possible.

Thanks

like image 428
Chris Meek Avatar asked Dec 31 '22 05:12

Chris Meek


1 Answers

You could create a DTO class that you use for reporting / overviews for instance... This class could look like this:

public class PersonView
{
     public string Name{ get;set; }
     public int NumberOfSubordinates{get;set;}     
}

Then, you create a Criteria query, in in that Criteria you define that you want to retrieve all Persons. However, you can specify that NHibernate should not return Person objects, but PersonView objects. In order to be able to do this, you'll need to use a projection and an AliasToBeanTransformer:

ICriteria crit = new Criteria(typeof(Person));

crit.SetProjection (Projections.ProjectionList()
                       .Add (Projections.Property("Name"), "Name")
                       .Add (Projections.Count ("Subordinates"), "NumberOfSubordinates");

crit.SetResultTransformer(Transformers.AliasToBean (typeof(PersonView));

Something like the above. (I didn't test your specific situation). Then, you just have to let NHibernate know of the existence of the PersonView class, by simply 'importing' this class. I have one hbm.xml file, where I import all my DTO classes. This looks like

<hibernate-mapping .. >
  <import class="PersonView" />
</hibernate-mapping>

Then, NHibernate will generate a query for your Criteria that pretty much looks like:

SELECT p.Name, COUNT(p.Subordinates) FROM Person
INNER JOIN Subordinates ON Person.PersonId = Subordinates.PersonID
GROUP BY p.Name
like image 63
Frederik Gheysels Avatar answered Jan 15 '23 07:01

Frederik Gheysels