在.net 4.5中有类似dbgeometry makevalid的东西吗?

我正在尝试计算折线的面积

string poly = "POLYGON ((637604.918432772 2230520.64934531, 637622.257266129 2230419.44632915, 637279.107128549 2230192.04910755, 636765.470527745 2230179.6468564, 636778.005055813 2229861.77192838, 636529.81646905 2229464.29327025, 635813.486592791 2229523.30345774, 636017.385069448 2229974.32341381, 636267.323659164 2230070.32127916, 637035.026966561 2230404.70764784, 637275.265066307 2230401.13408429, 637604.918432772 2230520.64934531, 637604.918432772 2230520.64934531))"; DbGeometry gm = DbGeometry.FromText(poly, 32637); double area= gm.Area.Value; // here I got the error Exception has been thrown by the target of an invocation. 

后来我注意到dbgeometry无效的错误共鸣我尝试ms sql 2012中的代码也给我错误但是当我尝试那样的时候

 SELECT @gm.MakeValid().STArea() 

多数民众赞成在sql工作我的问题是,有什么东西使几何有效.net谢谢你

除非您使用entity framework,否则我同意Bojan的观点?

SqlGeometry对象具有MakeValid()函数,因此使用您的示例,允许在DbGeography和SqlGeography之间进行转换:

 DbGeography geog; SqlGeometry geom = SqlGeometry.STGeomFromWKB(new SqlBytes(geog.AsBinary()), 32637); 

但是,除非您使用EF,否则我建议您只使用SqlGeometry

  1. 没有演员/转换
  2. SqlGeometry具有比DbGeometry更多的可用function。

希望有所帮助。

你绝对不应该去DB获得你想要的东西。 一种简单快速的方法是通过向您的项目添加以下代码来扩展DbGeography:

 using System.Data.SqlTypes; using Microsoft.SqlServer.Types; namespace System.Data.Spatial { public static class DbGeometryExtension { public static DbGeometry MakeValid(this DbGeometry geom) { if (geom.IsValid) return geom; return DbGeometry.FromText(SqlGeometry.STGeomFromText(new SqlChars(geom.AsText()), 4326).MakeValid().STAsText().ToSqlString().ToString(), 4326); } } } 

创建此代码时会做出一些假设,因此请不要“按原样”使用它。

SqlSpatialFunctions.MakeValid是一种特定于SQL Server的方法。

如果您对几何体无效的原因感兴趣,可以询问SQL Server:

 SELECT @gm.IsValidDetailed() 

此外,您可能需要考虑直接使用SQL Server几何类型: SqlGeometry.MakeValid

在这里,一个媒介解决了这个问题,我做了像那样的scallar函数

 CREATE FUNCTION [dbo].[GeomMakeValid](@geom as geometry) RETURNS geometry AS BEGIN DECLARE @gm as geometry; set @gm = @geom.MakeValid(); return (@gm); END GO 

然后我从那样的模型中调用它

 public static DbGeometry geoMakeValid(DbGeometry geom) { EntityConnection Connec = getConnection(); DbCommand com = Connec.StoreConnection.CreateCommand(); com.CommandText = "select dbo.GeomMakeValid(@geom)"; com.CommandType = System.Data.CommandType.Text; com.Parameters.Add(new SqlParameter("@geom", geom.AsText())); if (com.Connection.State == ConnectionState.Closed) com.Connection.Open(); try { var result = com.ExecuteScalar(); // should properly get your value Connec.Close(); return DbGeometry.FromText( result.ToString(),geom.CoordinateSystemId); } catch (System.Exception e) { } Connec.Close(); return geom; } 

任何代码的任何部分我可以调用此函数使几何有效