I am performing distance calculations between addresses. Specifically the distance between a User and a particular location. I can build the LINQ queries that cause the database to calculate the distance and order the results by that distance. However, I can’t find a way to RETURN that distance in the Entities. A simplified version of the query is below:
public IQueryable<Place> GetPlacesWithinRadiusOfUser(double userLongitude, double userLatitude, int miles )
{
return (from Place in this.ObjectContext.Places
where RadiusOfEarth * Math.Acos((double)
(Math.Sin((double)Place.Addresses.First().Latitude / DegreesToRadians) * Math.Sin(userLatitude / DegreesToRadians))
+
(Math.Cos((double)Place.Addresses.First().Latitude / DegreesToRadians) * Math.Cos(userLatitude / DegreesToRadians)
* Math.Cos((userLongitude / DegreesToRadians) - ((double)Place.Addresses.First().Longitude / DegreesToRadians))
)
)
<= miles
select Place);
}
Essentially, the math from above I need to return as a Distance property on the Address Entity (which is child of Place). I have created the following partial class and the field does appear in the silverlight client.
public partial class Address
{
//The Distance field is used to return a distance if a reference point is provided in a query
[DataMember]
public Nullable<decimal> Distance { get; set; }
}
So, the Distance property and calculation is dependent on the parameters of the GetPlacesWithinRadiusOfUser method.
Is there a way to get the parameters from the query to the Address Entity so that I can perform the same calculation and have it available in the Entity upon arriving at the client?
I can certainly create a client side routine that will do this calculation but this will get messy as I will have to continually inject that in every UI that needs it. I would much prefer to return it in the Entity so that I can just bind to it and display it (essentially I want a calculated field returned from SQL). If it were striaght SQL, this would be trivial but I am at a loss as to how to do this with RIA Services and the Entity Framework.
And thoughts?
With Entity Framework, I was never able to find a way to actually do this (the way I wanted to). However, I found a pretty good solution. Steps are as follows:
Created the query by issuing the distance calculation on the ObjectContext….then filtered a Place query by the returned values. All of that is done in one query call from the client. It doesn’t return the distance…but I handled that a different way.
I then created extension methods on all of the relavent objects like so:
Then, anywhere I needed to get the distance, I could do something like User.DistanceTo(myAddress)
This actually worked out a little better because I could then reuse the same extension methods no matter what the situation.