以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,之后再做補充。