1. 程式人生 > 其它 >ASP.NET/ EF Core/ NetTopologySuite 使用GeoJSON進行資料傳輸

ASP.NET/ EF Core/ NetTopologySuite 使用GeoJSON進行資料傳輸

以Postgresql為例,首先安裝依賴:

dotnet add package NetTopologySuite 
dotnet add package Npgsql.NetTopologySuite 

對於一個Location資料:

[Table("location")]
public class Location 
{
  public string Name {get;set;}
  public NetTopologySuite.Geometries.LineString? Geom {get;set;}
}

以.net6為例,通過在Program.cs中新增GlobalTypeMapper

NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();

之後需在為自己的DbContext新增如下配置:

builder.Services.AddDbContext<MyDbContext>(options =>
    options
        .UseNpgsql("your-db-connection-string", x => x.UseNetTopologySuite())
);

至此,已完成模型>>PostGIS型別的對映,當寫好Controller希望測試新增記錄的介面的時候,會發現好像沒有一個合適的方法來進行資料傳輸。

我想偷懶,測試了兩種比較通用的明文格式GeoJSON和WKT作為描述:

{
  "Name":"example",
  "Geom":{
    'type': 'LineString',
    'coordinates': [
      [122.483696, 37.833818],
      [122.492237, 37.833378],
      [122.493782, 37.833683]
    ]
   }
}
···
{
  "Name":"example",
  "Geom":"LINESTRING (30 10, 10 30, 40 40)"
}

得到了一樣的結果:

Unable to find a constructor to use for type NetTopologySuite.Geometries.LineString

看來Npgsql/NetTopologySuite沒有定義隱式的轉換,因此需要宣告一個JsonConverter來強制執行這一轉換,參考這個問題

https://github.com/NetTopologySuite/NetTopologySuite.IO.GeoJSON/issues/17#issuecomment-441620819

我們首先需要新增NetTopologySuite的GeoJSON拓展

dotnet add package NetTopologySuite.IO.GeoJSON

之後新增為空間欄位新增JsonConverter:

[Table("location")]
public class Location 
{
  public string Name {get;set;}
  [Newtonsoft.Json.JsonConverter(typeof(NetTopologySuite.IO.Converters.GeometryConverter))]
  public NetTopologySuite.Geometries.LineString? Geom {get;set;}
}

這樣,通過下面的Request Body就可以正確的解析出空間欄位了。

{
  "Name":"example",
  "Geom":{
    'type': 'LineString',
    'coordinates': [
      [122.483696, 37.833818],
      [122.492237, 37.833378],
      [122.493782, 37.833683]
    ]
   }
}

[HttpPost("line")]
public IActionResult AddLocation([FromBody] Location location)
{
    _myDbContext.Locations.Add(location);
    _myDbContext.SaveChanges();
    return Ok();
}

綜上完成了nts-postgis的型別對映,實現了通過GeoJSON的資料傳輸,但如果使用Swagger UI的話,NTS的Geometry型別的Example Value是一個複雜的結構體,不方便通過Swagger UI除錯,至於修改空間欄位的Example Value,之後再做補充。

站外部落格地址:https://blog.yuhang.ch