【发布时间】:2013-02-27 09:05:26
【问题描述】:
也许我错过了什么。我有一个“地理”数据类型的 sql server 列。
我想在我的 c# 代码中使用 DbGeography 类型。有什么方法可以将 sql 的 geography 转换为 dbgeography?
【问题讨论】:
标签: sql-server c#-4.0 gis geospatial spatial
也许我错过了什么。我有一个“地理”数据类型的 sql server 列。
我想在我的 c# 代码中使用 DbGeography 类型。有什么方法可以将 sql 的 geography 转换为 dbgeography?
【问题讨论】:
标签: sql-server c#-4.0 gis geospatial spatial
很抱歉回复晚了 - 但在搜索其他内容时看到了这个。
只需执行以下操作:
SqlGeography theGeography;
int srid = 4326; // or alternative
DbGeography newGeography = DbGeography.FromText(theGeography.ToString(), srid);
反转它:
DbGeography theGeography;
SqlGeography newGeography = SqlGeography.Parse(theGeography.AsText()).MakeValid();
希望有帮助!
【讨论】:
当性能很重要时,应该使用众所周知的二进制而不是众所周知的文本:
var newGeography = DbGeography.FromBinary(theGeography.STAsBinary().Value);
使用 SRID 会导致过载,如果这很重要的话。在我对 1000 个相当复杂的多边形的简单测试中,基于二进制的方法比基于文本的方法快 4 倍:
* Binary-based conversion
Run 1: 1948
Run 2: 1944
Run 3: 1959
Run 4: 1979
Run 5: 1988
Average: 1963.6
* Text-based conversion
Run 1: 8527
Run 2: 8553
Run 3: 8596
Run 4: 8535
Run 5: 8496
Average: 8541.4
【讨论】:
SqlGeography.STGeomFromWKB(new SqlBytes(value.AsBinary()), value.CoordinateSystemId)
如果您没有运行 EF6,则提供的解决方案似乎没问题。 使用早期版本没问题,但是使用 EF6,我们不应该引用这个程序集。 这让 EF 有点疯狂。
【讨论】:
根据我在 ILSpy 中对 EntityFramework.SqlServer.dll 的阅读,我认为从 SqlGeography 转换为 DbGeography 的最快方法是:
var dbGeo = System.Data.Entity.SqlServer.SqlSpatialServices.Default.GeographyFromProviderValue(sqlGeo);
这种方法的优点是不需要二进制转换和解析。它只是使用 SqlGeography 作为内部提供程序值返回一个 DbGeography。
【讨论】:
我发现这是一个可行的解决方案:
int coordSys = DbGeography.DefaultCoordinateSystemId; // 4326;
SqlGeography g = SqlGeography.Point(lat, lon, coordSys);
return DbSpatialServices.Default.GeographyFromProviderValue(g);
没有序列化/转换为会降低性能的字符串 (WKT) 或二进制 (WKB)。
它在 EF 6.1.3、SqlServer 2016 SP1 和 Microsoft.SqlServer.Types.14.0.314.76 上为我工作
【讨论】: