You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core+PostgreSQL计算两点距离遇st_x(geography)不存在错误

解决PostGIS中function st_x(geography) does not exist错误

错误核心原因:你的Location字段映射的是PostGIS的geography类型,但EF Core解析x.Location.X时会生成SQL函数ST_X(),而PostGIS的ST_X()仅支持geometry类型,不兼容geography类型,因此抛出该错误。以下是具体解决步骤:

1. 替换经纬度获取方式

将x.Location.X和x.Location.Y替换为PostGIS针对geography类型的专用函数ST_Longitude()和ST_Latitude(),在EF Core中通过EF.Functions调用这些数据库函数:

Longitude = EF.Functions.StLongitude(x.Location),
Latitude = EF.Functions.StLatitude(x.Location),

2. 修正距离计算逻辑

geography类型的距离计算需使用ST_Distance()函数,同时要确保传入的用户位置转为geography类型(匹配Location字段类型),修改后的距离计算代码如下:

DistanceFromUser = EF.Functions.StDistance(
    x.Location, 
    new Point(filter.UserLongitude, filter.UserLatitude).ToGeography()
),

3. 确认实体类的Location字段配置

确保Point实体中Location字段正确映射为PostGIS的geography类型,可通过Fluent API配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Point>()
        .Property(p => p.Location)
        .HasColumnType("geography (point)");
}

最终修改后的完整代码

var pointsQueryable = _context.Points;
var points = pointsQueryable.Select(x => new PointViewModel
{
    Id = x.Id,
    Title = x.Title,
    Address = x.Address,
    Description = x.Description,
    Longitude = EF.Functions.StLongitude(x.Location),
    Latitude = EF.Functions.StLatitude(x.Location),
    Image = x.Image,
    DistanceFromUser = EF.Functions.StDistance(
        x.Location, 
        new Point(filter.UserLongitude, filter.UserLatitude).ToGeography()
    ),
});

注意:需确保项目已安装NetTopologySuite和NetTopologySuite.Postgis NuGet包,否则无法使用这些地理空间函数。

内容的提问来源于stack exchange,提问作者Showechy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:09:57