Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort in (n)hibernate on a property of a child object?

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!

like image 677
David Rubin Avatar asked Dec 13 '22 03:12

David Rubin


1 Answers

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.

like image 195
ChssPly76 Avatar answered Mar 07 '23 15:03

ChssPly76