也许我漏掉了什么。我有一个SQL Server列,数据类型为“Geography”。
我想在我的C#代码中使用DbGeography类型。有没有将SQL的geography转换为dbgeography的方法或者进行强制转换?
我想在我的C#代码中使用DbGeography类型。有没有将SQL的geography转换为dbgeography的方法或者进行强制转换?
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很重要,那么可以使用超载函数。在我的一千个相当复杂的多边形的简单测试中,基于二进制的方法比基于文本的方法快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)
- Marc Gravell根据我在ILSpy中读取EntityFramework.SqlServer.dll的内容,我认为从SqlGeography转换为DbGeography的最快方法是:
var dbGeo = System.Data.Entity.SqlServer.SqlSpatialServices.Default.GeographyFromProviderValue(sqlGeo);
如果您没有运行EF6,提供的解决方案似乎是可以的。 对于早期版本来说,这没问题,但是对于EF6,我们不应该引用这个程序集。 它会让EF有些疯狂。
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上已经测试通过。
DBGeography.FromText(theGeography.ToString(), theGeography.STSrid.Value)
。 - Anthony Mills