Entity Framework Distance Query

SQL Server has a table that contains columns Latitude

and Longitude

. We want to query for the closest location from a specific point using a query:

SELECT TOP (1) 
    [ID], [Lat], [Lng],
    geography::Point(32, 34, 4326).STDistance(geography::Point([Lat], [Lng], 4326)) as Dist
FROM 
    [Area]
ORDER BY 
    Dist

      

Is there a way to do this with EF and let SQL Server do distance calculations?

thank

+3


source to share


1 answer


The simplest solution I've come across is to just use a raw request and EF Core (I assume you are using it) will do the rest.

var blogs = context.Blogs
.FromSql("SELECT * FROM dbo.Blogs")
.ToList();

      

More details on raw requests here https://docs.microsoft.com/en-us/ef/core/querying/raw-sql



Also, as mentioned in the comments for your question, you need to add WHERE

to your query to make it work faster. Something like that

WHERE [Latitude] < TopLatBound 
    AND [Latitude] > BottomLatBound 
    AND [Longitude] > LeftLngBound 
    AND [Longitude] < RightLngBound

      

You can calculate the snapping by converting your desired max distance to lat and long as described here https://gis.stackexchange.com/questions/142326/calculating-longitude-length-in-miles

0


source







All Articles