4

I have an object from my domain model that has a child object. How can I use a criteria query to order based on a property of the child?

For example:

class FooType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public BarType Bar { get; set; }
}

class BarType
{
    public int Id { get; set; }
    public string Color { get; set; }
}

...

// WORKS GREAT
var orderedByName = _session.CreateCriteria<FooType>().AddOrder(Order.Asc("Name")).List();

// THROWS "could not resolve property: Bar.Color of: FooType"
var orderedByColor = _session.CreateCriteria<FooType>().AddOrder(Order.Asc("Bar.Color")).List();

What do I need to do to enable this scenario? I'm using NHibernate 2.1. Thanks!

1 Answer 1

13

You need to either add an alias or create a nested criteria for your child. Not sure how to do this in NHibernate, in Hibernate it's done via createCriteria() and createAlias() methods. You would then use the alias as prefix in order by.

Update Hibernate code sample:

Criteria criteria = session.createCriteria(FooType.class);
criteria.createAlias("bar", "b");
criteria.addOrder(Order.asc("b.color"));

I imagine in NHibernate it would be quite similar, though with property/entity names uppercased. Here's an example from NHibernate documentation.

1
  • Can you give me a code sample? I'm not sure I understand what you mean. Aug 12, 2009 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.