【问题标题】:How to read a `geography` column by `SqlDataReader`?如何通过“SqlDataReader”读取“geography”列?
【发布时间】:2014-08-14 19:53:20
【问题描述】:
我有一个带有geography 列的 SQL Server 2008 数据库,该列由 Entity Framework 6.0.0-alpha3 中的System.Data.Entity.Spatial.DbGeography 生成。
现在我需要使用SqlDataReader 阅读该专栏。但我不知道该怎么做。使用旧上下文不是一种选择。我尝试将其转换为DbGeography:
Location = (DbGeography)reader.GetValue(index)
但我收到此错误:
无法转换类型为“Microsoft.SqlServer.Types.SqlGeography”的对象
输入“System.Data.Entity.Spatial.DbGeography”
你有什么建议吗?
【问题讨论】:
标签:
sql-server
entity-framework
sqldatareader
geography
sqlgeography
【解决方案1】:
嗯,很简单。我只是感到困惑。但我不会删除问题,而是将答案发布给有相同问题的其他人。
// read the value as dynamic:
dynamic temp = reader.GetValue(index);
// the temp contains Lat and Long properties:
var text = string.Format("POINT({0:R} {1:R})", temp.Long, temp.Lat);
// the temp also contains the STSrid as coordinate system id:
var srid = temp.STSrid.Value;
// the rest is really simple:
Location = System.Data.Entity.Spatial.DbGeography.PointFromText(text, srid);
【解决方案2】:
如果你的地理是一个点,你可以使用:
选择 MyColumn.Lat、MyColumn.Long ...
reader.GetDouble(0);
reader.GetDouble(1);