林克不支持的数据类型(地理)
因此,Linq 不支持 Geography
数据类型,这给可爱的“将表格拖到 Linq 设计图面”开发模型的工作带来了很大麻烦。
有什么方法可以扩展 Linq 以使用 Geography 数据类型吗? 或者,每当我需要使用地理列时,我是否需要构建一个全新的数据层和一组查询?
我已经被这个问题困扰了几天,无法弄清楚是否可能。
So, Linq does not support the Geography
data type, which throws a major spanner in the works in the lovely 'drag table onto the Linq design surface' developemnt model.
Is there any way that I can extend Linq to work with the Geography datatype?
Or will I need to build a whole new datalayer and set of queries for whenever I need to use Geography columns?
I've been stuck on this for a few days and can't work out if it's possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将列转换为 varbinary(max),Linq to SQL可以处理。避免在每个查询中执行此操作的一种方法是添加定义为
CAST(GeographyColumn AS varbinary(max))
的计算列。获得
byte[]
数据后,您可以编写一个简短的实用方法,使用MemoryStream 将其转换为实际的
和Microsoft.SqlServer.Types.SqlGeography
类IBinarySerialize
.Read
/Write
方法。据我所知,如果您需要使用任何 CLR 类型(包括地理、几何、hierarchyid 和任何自定义类型),这是唯一可行的解决方案 - Linq 并不“原生”支持其中任何类型。编写所有样板代码有点痛苦,但是您可以通过一些扩展方法使其变得更容易。
您将无法以这种方式查询列;但是,您可以使用 Linq 动态查询库。您不会拥有智能感知或其他一些 Linq 功能,但它仍然是可组合的,因此比手工制作每个查询更好,并且您可以获得强类型结果。
更新:我找到了一个稍微干净的解决方案 这里。您可以这样使用设计器;只需将
SqlGeography
包装器属性添加到分部类,并将STGeomFromWKB
方法与SqlBytes
类一起使用即可。不过,这仍然无法为您提供内联查询功能。Cast the column to a varbinary(max), which Linq to SQL can handle. One way to avoid doing this in every query is just to add a computed column defined as
CAST(GeographyColumn AS varbinary(max))
.Once you have the
byte[]
data, you can write a short utility method to convert it to the actualMicrosoft.SqlServer.Types.SqlGeography
class using aMemoryStream
and theIBinarySerialize
.Read
/Write
methods.As far as I know, this is the only working solution if you need to work with any CLR type, including geography, geometry, hierarchyid, and any custom types - Linq doesn't "natively" support any of them. It's a bit of a pain to write all the boilerplate code, but you can make it easier with a few extension methods.
You won't be able to query against the column this way; however, you can get what I would call halfway there using the Linq Dynamic Query Library. You won't have intellisense or some of the other Linq goodies, but it's still composable and therefore better than hand-crafting every query, and you can get strong-typed results.
Update: I found a slightly cleaner solution here. You can use the designer this way; just add the
SqlGeography
wrapper property to a partial class and use theSTGeomFromWKB
method with theSqlBytes
class. That still won't give you inline query capabilities, though.看起来像您必须自己手动将其映射/解析为您自己的 POCO 类型。
Looks like you'll have to manually map/parse it yourself to your own POCO type.