I have a entity 'Person' a person has a collection of Friends (also Person entities)
I want to get the first 10 Friends of a particular person, ordered by LatestLogin.
My best effort is:
public static IList<Person> GetFriends(Person person, int count)
{
Person personAlias = null;
Person friendAlias = null;
ICriteria criteria = NHibernateSessionManager.Instance.GetSession()
.CreateCriteria(typeof (Person), () => personAlias)
.CreateCriteria(() => personAlias.Friends, () => friendAlias, JoinType.LeftOuterJoin)
.AddOrder(() => friendAlias.LatestLogin, Order.Desc)
.开发者_如何学运维Add<Person>(p => p.ID == person.ID)
.SetMaxResults(count);
return criteria.List<Person>();
}
Which Does grab all the users friends, but they are not ordered by LatestLogin. Any ideas?
I know it may sound weird but the solution is to change the line:
.AddOrder(() => friendAlias.LatestLogin, Order.Desc)
with:
.AddOrder(() => personAlias.LatestLogin, Order.Desc)
You have to see it the other way around in order to understand why this is necessary and not obvious at the beginning.
You are requesting Person objects (personAlias) that have the same 'Parent' friend (friendAlias) with ID == person.ID (.Add(p => p.ID == person.ID)) therefore you need to sort by the personAlias.LatestLogin and NOT the friendAlias.LatestLogin.
精彩评论