views:

38

answers:

1

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  A: 

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.

tolism7
Thanks this worked great! I have got a related question available at http://stackoverflow.com/questions/1718857/nhibernate-lambda-extensions-eager-loading-a-collections-assosciations That you will probably be able to answer if you want another 15 points! :) Thanks so much for your help!
reach4thelasers
Hey dude, any ideas about this NHibernateLambdaExtensions Question? http://stackoverflow.com/questions/1809247/nhlambdaextensions-create-a-criterion-object-to-add-to-icriteria-later
reach4thelasers