10

Is there a simple way to convert between SqlGeometry and DbGeometry? I'm using a popular sql spatial helper library and all of the functions in there expect SqlGeometry. But when i use Entity Framework against an ESRI ArcSDE feature class the Shape field is returned as a DbGeometry. I can't call any of the methods I would like to (such as LocateAlongGeom) with that DbGeometry type. Maybe there is a way to serialize it as binary or text then read it back in as a SqlGeometry?

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
VBAHole
  • 1,508
  • 2
  • 24
  • 38

3 Answers3

12
//Convert from SqlGeometry to DbGeometry 
SqlGeometry sqlGeo = ...
DbGeometry dbGeo = DbGeometry.FromBinary(sqlGeo.STAsBinary().Buffer);

//Convert from DBGeometry to SqlGeometry
 SqlGeometry sqlGeo2 = SqlGeometry.STGeomFromWKB(new SqlBytes(dbGeo.AsBinary()), 0);
BizarroDavid
  • 745
  • 8
  • 9
  • 2
    Shouldn't the `DbGeometry` to `SqlGeometry` conversion be... `SqlGeometry sqlGeo2 = SqlGeometry.STGeomFromWKB(new SqlBytes(dbGeo.AsBinary()), dbGeo.CoordinateSystemId);` To account for geometries that aren't in SRID-0? – Xharlie Oct 15 '14 at 09:57
  • 1
    Yes, I would assume you'd want to pass in the SRID in most cases. For most GPS coordinates you'd use `4326` for WGS84. http://spatialreference.org/ref/epsg/4326/ – jocull Apr 13 '15 at 15:17
  • I believe you can also detect it dynamically using `dbGeo.CoordinateSystemId` in place of the zero above. – jocull Apr 13 '15 at 15:40
3

An easy way to manage multiple spatial types is via extension methods, like so: (using slightly modified versions of the code samples from @BizarroDavid)

public static class GeometryExtensions
{
    public static DbGeometry ToDbGeometry(this SqlGeometry sqlGeometry)
    {
        return DbGeometry.FromBinary(sqlGeometry.STAsBinary().Buffer);
    }

    public static SqlGeometry ToSqlGeometry(this DbGeometry dbGeometry)
    {
        return SqlGeometry.STGeomFromWKB(new SqlBytes(dbGeometry.AsBinary()), dbGeometry.CoordinateSystemId);
    }
}

Once you have them implemented, you can use them like so...

DbGeometry anyDbGeometry;
SqlGeometry anySqlGeometry;

//Convert to DbGeometry
anyDbGeometry = anySqlGeometry.ToDbGeometry();

//Convert to SqlGeometry
anySqlGeometry = anyDbGeometry.ToSqlGeometry();
jocull
  • 20,008
  • 22
  • 105
  • 149
1

Entity Framework doesn't support CURVES (CIRCLE) -> change to lines:

return DbGeometry.FromBinary(sqlGeometry.**STCurveToLine()**.STAsBinary().Buffer);
ouflak
  • 2,458
  • 10
  • 44
  • 49