Select to view content in your preferred language

Convert Polygon to DbGeography

687
3
09-08-2022 02:17 PM
AlexVelez
Occasional Contributor

Hello

I need to convert a polygon geometry to System.Data.Entity.Spatial.DbGeography , I have been trying to do with something like that

 

 StringBuilder text = new StringBuilder();
                string firstPoint = string.Empty, textToAppend;
                var parts = ((Polygon)(geometry)).Parts;
                for (int i = 0; i < parts[0].Points.Count; i++)
                {
                    var normalizedPoint = GeometryEngine.NormalizeCentralMeridian(parts[0].Points[i]);
                    var projectedCenter = GeometryEngine.Project(normalizedPoint, SpatialReferences.Wgs84) as MapPoint;
                    textToAppend = $"{projectedCenter.X} {projectedCenter.Y}";
                    textToAppend= textToAppend.Replace(',', '.');
                    textToAppend = $"{textToAppend},";
                    text.Append(textToAppend);
                    if (string.IsNullOrWhiteSpace(firstPoint))
                    {
                        firstPoint = $"{projectedCenter.X} {projectedCenter.Y}";
                        firstPoint = firstPoint.Replace(',', '.');
                    }
                }
                text.Append(firstPoint);
             var dbGeography=DbGeography.PolygonFromText($"POLYGON(({text}))", 4326);

 And it works, but when i saved it to a SQL database on a column of type Geography, it does not work correctly.

What is the correct way to achieve this?

Thanks

0 Kudos
3 Replies
dotMorten_esri
Esri Notable Contributor

You're better off going through the geometry builders than going through WKT which would be extremely slow. Perhaps this code snippet here will help: https://github.com/dotMorten/GeometryConversions/blob/master/src/GeometryConversions.Shared/System.S...

0 Kudos
AlexVelez
Occasional Contributor

Thanks for the reply 

I was checking the code but its for convert to Microsoft.Spatial and i dont know what more to do to convert to System.Data.Entity.Spatial.DbGeography. Please help me

 

 

 

 

 

0 Kudos
dotMorten_esri
Esri Notable Contributor

I don't know EF too well, but browsing their code it looks like it's just a wrapper around other spatial libraries, and there's some sort of provider that might give you access to the underlying sql geometry libraries.