Returning Entities + Extra Data with ADO.NET Data Services

entity-frameworklinqnetwcf-data-services

Trying to figure out the best way to accomplish this. So I have a table of Stores with properties:

StoreID, Name, Latitude, Longitude, etc.

I'm using ADO.NET Data Services (Astoria) to create a web service that will show nearby stores given a radius and a coordinate. I made a Service Operation to take the params and return the results as an IQueryable. So far so good.

So right now I have something like:

return context.Stores.Where(...distance calculation...);

This works great, but I also want to return the distance of each store from the given radius. I have the calculation covered, but how should I include the distance along with the store data? Should I make a class like StoreSearchResult with properties for the Store and the Distance?

If I was just using SQL, I could write a single database query that would return all of the data for the Store, along with a column for the distance. Something like:

Select StoreID, Name, Latitude, Longitude, (calculation...) as Distance 
from Store
where ...distance param...

So I'm looking for the best way to send back the original Store data + the distance calculation while still returning IQueryable. I'd prefer not to take an IEnumerable and use AsQueryable…I just feel like it should be possible to keep it "close" to the database query, and I'm probably just missing something.

Best Answer

It may be better to write a struct that holds store and distance then just add those to a list of matches

List<StoreSearchResult> matches = new List<StoreSearchResult>();
foreach (Store store in Stores)
{
  int distance = ...distance calc...
  if (distance < searchArea)
  {
    matches.Add(new StoreSearchResult(store, distance);
  }
}
return matches;

Or, you could just add the current search distance as a variable on the Store class (which seems messy to me) to store distance, and then a method that will calculate it and update the distance value as well as return it.

int CalcDistance(lat, long)
{
  ... do some calc...
  this.CurrentSearchDistance = results;
  return results;
}

then...

return context.Stores.Where(store => store.CalcDistance(lat,long) < searchArea);