C
C#2y ago
barcode

❔ IQueryable implementation

I have a query that I want to order by location
.OrderBy(x => (x as ILocatable).DistanceTo(request.Longitude, request.Latitude))
.OrderBy(x => (x as ILocatable).DistanceTo(request.Longitude, request.Latitude))
however I get an error
System.InvalidOperationException: The LINQ expression 'DbSet<City>()
.OrderBy(c => ((c as ILocatable)).DistanceTo(
longitude: __request_Longitude_0,
latitude: __request_Latitude_1))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
System.InvalidOperationException: The LINQ expression 'DbSet<City>()
.OrderBy(c => ((c as ILocatable)).DistanceTo(
longitude: __request_Longitude_0,
latitude: __request_Latitude_1))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
which is expected, the function:
public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

var dLat = (latitude - Latitude) * Math.PI / 180;
var dLon = (longitude - Longitude) * Math.PI / 180;
var lat1 = Latitude * Math.PI / 180;
var lat2 = latitude * Math.PI / 180;

var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

var dLat = (latitude - Latitude) * Math.PI / 180;
var dLon = (longitude - Longitude) * Math.PI / 180;
var lat1 = Latitude * Math.PI / 180;
var lat2 = latitude * Math.PI / 180;

var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
is it feasible to implement the translation or should I just do AsEnumerable?
4 Replies
TimberStalker
TimberStalker2y ago
I think this is an issue with EntityFramework not Linq
Angius
Angius2y ago
Well, yes
TimberStalker
TimberStalker2y ago
If you want you can look up c# expression trees, which is the feature used for translating the query
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server