C#C
C#3y 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))


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.


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;
    }


is it feasible to implement the translation or should I just do AsEnumerable?
Was this page helpful?