0

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?

1
  • I would suggest using SQL Profiler (if you are using SQL Server) to get the generated query and examine what is really generated and why it does not work as SQL query. Maybe also sharing that with us... Is the Friends property a many-to-many with Person through an association table? Nov 11, 2009 at 10:09

1 Answer 1

1

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.

2

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.