Ok, here’s my problem. I have database table BloodCenters, which have latitude and longitude field. I want to query those table by using Linq Lambda Syntax by retrieving the BloodCenters which are inside the given radius relative to some point.
I am using this code, but it still give me error (inside the Where predicate):
public static List<BloodCenter> GetAllNearby(int latitude, int longitude, int radius, int limit){
List<BloodCenter> res = null;
res = new DBEntities().BloodCenters.Where(b =>
Util.distance(latitude, longitude, b.Latitude, b.Longitude, "K") <= radius).Take(limit);
return res;
}
Util.distance is a function returning a distance between 2 point of latitude and longitude.
Edited
So, I can’t put my own function inside the Where predicate. But can I compute the distance using SQL Syntax? Here’s my Util.Distance implementation:
public static double distance(double lat1, double longi1, double lat2, double longi2, string unit){
var theta = longi1 - longi2;
var dist = Math.Sin(DegreeToRadian(lat1)) * Math.Sin(DegreeToRadian(lat2)) +
Math.Cos(DegreeToRadian(lat1)) * Math.Cos(DegreeToRadian(lat2)) * Math.Cos(DegreeToRadian(theta));
dist = Math.Acos(dist);
dist = RadianToDegree(dist);
var miles = dist * 60 * 1.1515;
unit = unit.ToUpper();
if (unit.Equals("K"))
return miles * 1.609344;
else if (unit.Equals("N"))
return miles * 0.8684;
else
return miles;
}
That will not work because
Util.distanceis implemented in your C# code and the query surface has no idea how that would be translated to SQL (or even if that would be possible).An immediate workaround is to fetch all records from the database and apply the predicate to instances, like this:
Of course fetching all the records isn’t the best idea either, but sometimes there’s simply no other way.
What you could try is to inline the logic of
Util.distanceinside theWherepredicate. If the logic can be expressed using only “simple” operations (like basic math) the query surface would be able to translate it to SQL and everything would go smoothly.Here is a list of all methods that can be automatically translated to SQL.