Oliver
Oliver

Reputation: 11597

Order by a function result in NHibernate?

I have a table in my database containing geographical locations. I want to write a function that finds the location that is closest to a point. I tried this in NHibernate:

public Location GetClosestLocation(double latitude, double longitude)
{
    var closest = Session.QueryOver<Location>()
        .OrderBy(location => 
            (location.Latitude - latitude) + 
            (location.Longitude - longitude))
        .Asc.SingleOrDefault();

    return closest;
}

But it doesn't work - I get a runtime error.

What can I do to return the closest location? Is it possible to order by the result of a simple function with NHibernate?

Upvotes: 1

Views: 192

Answers (1)

Oskar Berggren
Oskar Berggren

Reputation: 5629

I don't think QueryOver can understand expressions like that - it's use of lambda expressions is limited to identifying properties. There is an overload of OrderBy() that takes an IProjection, which provides for more flexibility.

With LINQ you should be able to use almost the same code as you tried:

var closest = Session.Query<Location>()
                     .OrderBy(location => 
                                 (location.Latitude - latitude) + 
                                 (location.Longitude - longitude))
                     .SingleOrDefault();

Upvotes: 3

Related Questions