【问题标题】:Geospacial search - Entity Framework Core / PostgreSQL地理空间搜索 - Entity Framework Core / PostgreSQL
【发布时间】:2020-09-10 12:57:05
【问题描述】:

我有一个存储一些事件位置的表和一个使用 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; }
    }

问题
Location 类与 Post 具有 1 对 1 的关系。 现在,给定纬度和经度的输入以及 X 公里 的半径,我希望能够从该半径内的数据库中获取所有帖子。即我想执行地理空间查询。

我找到了一个解决方案,但它涉及执行一些简单的 SQL 查询,我会不惜一切代价避免这些查询。 我将如何使用 LINQ 执行它?

【问题讨论】:

  • 你这里说的radius X km是什么意思,不是字段,你Post类的结构是什么?

标签: c# postgresql linq asp.net-core entity-framework-core


【解决方案1】:

解决方案来自Postgis。它增加了对允许在 SQL 中运行位置查询的地理对象的支持。它必须安装在数据库端。对于服务器端,必须安装以下library

可以执行地理空间查询的相关方法称为“.IsWithinDistance”。 纬度,经度必须作为一个点传递,半径。这将返回指定范围内的所有记录。

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2023-02-03
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多