首页 > 解决方案 > .NET Core Entity Framework 保存空间地理数据类型 SQL Server

问题描述

我使用 Entity Core 2.2 开发了一个 ASP.NET Core 应用程序。此应用程序保存位置边界。

我正在使用 google.maps.drawing.DrawingManager 允许用户创建一个多边形,以便使用地理数据类型将边界保存到 SQL 服务器数据库。我将来需要检查特定的地理点是在这个多边形内部还是外部。

下面是调用 .NET Web API 的代码

function onPolygonComplete(e) {
    if (!cancelDrawingShape) {
        var Path= e.getPath();


        var thisData = {
            sPolygon: JSON.stringify(path.getArray())            };

        $.ajax({
            url: rootPath + 'Location/AddPolygon',
            data: thisData,
            type: 'POST',
            success: function (res) {
                e.setMap(null);
                removeAllFeatures();
                clientGeoFences = res.ClientGeoFences;
                refreshData(false);
            },
            failure: function (res) {

            }
        });

调用 API

public async Task<IActionResult> AddPolygon([FromForm] string sPolygon)
{
}

由于 Entity Core 不支持 Geography 数据类型,因此我按照建议安装了 NetTopologySuite (NTS)

https://docs.microsoft.com/en-us/ef/core/modeling/spatial

在为我的模型类搭建脚手架之后

具有地理数据类型的以下属性

public IGeometry StoreFence { get; set; }

我正在努力寻找如何使用 NetTopologySuite 类设置 StoreFence 属性以将多边形保存到数据库的示例。

使用 Entity Core/NetTopologySuite 将 google.maps.drawing.DrawingManager 多边形保存到数据库中的 SQL Server 地理类型列的任何示例都将非常棒。

标签: .netasp.net-core.net-core

解决方案


在使用柱安装NetTopologySuite和搭建数据库后,我得到了解决方案。Geography


我的模型有:

public IGeometry BoundsFence { get; set; }

作为Geography类型列的属性。


下面的代码将此属性设置为 WKT ( Well-Known Text ) 多边形:

IPolygon storeFence = (IPolygon)new WKTReader().Read(wktPolygon);

//Check if the orientation is not counter clock wise and reverse.
if (!storeFence.Shell.IsCCW)
    storeFence = (IPolygon)storeFence.Reverse();

storeFence.SRID = 4326;
store.StoreFence = storeFence;

await _dbContext.SaveChangesAsync();

推荐阅读