sco978
sco978

Reputation: 51

.NET Core Entity Framework Saving Spatial Geography Data Type SQL Server

I developing an ASP.NET Core application using Entity Core 2.2. This application saves location boundaries.

I am using google.maps.drawing.DrawingManager to allow users to create a polygon for saving boundaries to a SQL server database using geography data type. I need to in future check if specific geo points are inside or outside this polygon.

Below is the code that calls a .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) {

            }
        });

Called API

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

Since Geography datatype is not supported in Entity Core I Installed NetTopologySuite (NTS) as suggested

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

After scaffolding my model class

has the below property for Geography data type

public IGeometry StoreFence { get; set; }

I am struggling to find examples of how to now use NetTopologySuite classes to set StoreFence property to save the Polygon to the database.

Any examples of saving google.maps.drawing.DrawingManager polygons to SQL Server Geography type column in the database using Entity Core/NetTopologySuite will be great.

Upvotes: 1

Views: 4186

Answers (1)

sco978
sco978

Reputation: 51

I got the solution after installing NetTopologySuite and scaffolding the DB with Geography column.


My model has:

public IGeometry BoundsFence { get; set; }

As the property for Geography type column.


The code below will set this property to WKT (Well-Known Text) polygon:

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();

Upvotes: 3

Related Questions