我有一个表存储一些事件位置和一个使用 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 km 半径的输入,我希望能够从数据库中获取该半径内的所有帖子。即我想执行地理空间查询。
我找到了一个解决方案,但它涉及执行一些简单的 SQL 查询,我会不惜一切代价避免这些查询。 我将如何使用 LINQ 执行它?
最佳答案
解决方案来自Postgis 。它增加了对地理对象的支持,允许在 SQL 中运行位置查询。它必须安装在数据库端。对于服务器端,以下library必须安装。
可以执行地理空间查询的相关方法称为“.IsWithinDistance”。 纬度、经度必须作为点传递,以及半径。这将返回指定范围内的所有记录。
示例:
posts = await Context.Posts
.Include(p => p.Location)
.Where(p => p.Location.Location.IsWithinDistance(location, radius * 1000)
.AsNoTracking().ToListAsync();
关于c# - 地理空间搜索 - Entity Framework Core/PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976121/