4
votes

Considering the simplified class below, lets assume:

  • that the parent can have a relatively large amount of children (e.g. 1000)
  • the child collection is lazy loaded
  • we have loaded one parent via it's Id from a standard Get method of a ParentRepository, and are now going to read the OldestChild property
class Parent 
{
       public IList<Child> Children { get; set; }

       public Child OldestChild 
       {
         get { return Children.OrderByDescending(c => c.Age).FirstOrDefault();
       }

}

When using NHibernate and Repositories, is there some best practice approach to satisfy both:

  • a) Should select oldest child through the aggregate root (Parent) - [ie. without querying the children table independently via e.g. a ChildRepository using the Parent Id]

  • b) Should avoid loading the whole child collection into memory (ideally the oldest child query should be processed by the DB)

This seems something that should be both possible and easy, but I don't see an obvious way of achieving it. Probably I am missing something?

I'm using NHibernate 2.1, so a solution for that would be great, although will be upgrading to 3 soon.

2

2 Answers

2
votes

I would create a specialized method on your repository, which returns the oldest child of a given parent.

2
votes

You could map OldestChild using a Formula. Take a look at this to map a class to a formula: http://blog.khedan.com/2009/01/eager-loading-from-formula-in.html