也许我错过了什么。我有一个“Geography”数据类型的SQL Server列。
我想在我的c#代码中使用DbGeography类型。有什么方法可以从sql的地理位置转换或转换为dbgeography吗?
答案 0 :(得分:24)
对于迟到的回复感到抱歉 - 但在搜索其他内容时看到了这一点。
只需执行以下操作:
SqlGeography theGeography;
int srid = 4326; // or alternative
DbGeography newGeography = DbGeography.FromText(theGeography.ToString(), srid);
要扭转它:
DbGeography theGeography;
SqlGeography newGeography = SqlGeography.Parse(theGeography.AsText()).MakeValid();
希望有所帮助!
答案 1 :(得分:8)
当性能至关重要时,应该使用众所周知的二进制文件而不是众所周知的文本:
var newGeography = DbGeography.FromBinary(theGeography.STAsBinary().Value);
如果重要,则使用SRID会出现过载。在我使用1,000个相当复杂的多边形的简单测试中,基于二进制的方法比基于文本的方法快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
答案 2 :(得分:1)
如果您没有运行EF6,提供的解决方案似乎没问题。 早期版本没问题,但是使用EF6,我们不应该引用这个程序集。 它让EF litle变得疯狂。
答案 3 :(得分:1)
答案 4 :(得分:1)
基于我在ILSpy中读取的EntityFramework.SqlServer.dll,我相信从SqlGeography转换为DbGeography的最快方法是:
var dbGeo = System.Data.Entity.SqlServer.SqlSpatialServices.Default.GeographyFromProviderValue(sqlGeo);
此方法的优点是不需要二进制转换和解析。它只是使用SqlGeography作为内部提供者值返回DbGeography。
答案 5 :(得分:0)
我发现这是一个有效的解决方案:
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