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

落花浮王杯 提交于 2019-12-06 04:46:08

问题


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:


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.



来源:https://stackoverflow.com/questions/1269177/how-can-i-sort-in-nhibernate-on-a-property-of-a-child-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!