简体   繁体   中英

Geospacial search - Entity Framework Core / PostgreSQL

I have a table storing some events locations and a class mapped to it with ef core:

public class Location
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        
        [Column(TypeName = "geography (point)")]
        public Point Location { get; set; }

        public string? Address { get; set; }

        public string? City { get; set; }

        public string? Region { get; set; }

        public string? Country { get; set; }

        public Post Post { get; set; }

        public int PostId { get; set; }
    }

The Problem
The Location class has a 1 - 1 relationship with the Post. Now, given an input of latitude and longitude and radius of X km , I want to be able to get all posts from the database within that radius. ie I want to perform a geospacial query.

I found a solution but it involves performing some plain SQL queries which I try to avoid at all costs. How would I perform it with LINQ?

The solution comes from Postgis . It adds support for geographic objects allowing location queries to be run in SQL. It has to be installed on the DB side. For the server-side, the following library has to be installed.

The relevant method that can perform a geospatial query is called ".IsWithinDistance". The latitude, longitude have to be passed as a Point, and the radius. That will return all records within the specified range.

Example:

posts = await Context.Posts
        .Include(p => p.Location)                
        .Where(p => p.Location.Location.IsWithinDistance(location, radius * 1000) 
        .AsNoTracking().ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM