且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有可能使用SqlGeography与LINQ to SQL的?

更新时间:2023-11-28 22:16:58

空间类型不被支持的LINQ到SQL。支持不是不是很大 - 这是不存在的。

Spatial types are not supported by Linq to SQL. Support is not "not great" - it's nonexistent.

您的可以的阅读为BLOB,但你不能这样做,只需在LINQ的更改列类型为SQL。您需要在数据库级别来改变你的查询返回列作为 VARBINARY ,使用 CAST 语句。您可以通过添加一个计算 VARBINARY 列,它的LINQ会高兴地映射到一个字节[] 在表级别做到这一点>。

You can read them as BLOBs, but you can't do that by simply changing the column type in Linq to SQL. You need to alter your queries at the database level to return the column as a varbinary, using the CAST statement. You can do this at the table level by adding a computed varbinary column, which Linq will happily map to a byte[].

在换句话说,一些DDL是这样的:

In other words, some DDL like this:

ALTER TABLE FooTable
ADD LocationData AS CAST(Location AS varbinary(max))

然后,从您的LINQ删除位置列SQL类,并使用 LocationData ​​ code>代替。

Then, remove the Location column from your Linq to SQL class, and use LocationData instead.

如果您再需要访问的实际 SqlGeography 例如,你需要将其转换为从字节数组,使用的STGeomFromWKB 并的STAsBinary

If you then need access to the actual SqlGeography instance, you'll need to convert it to and from the byte array, using STGeomFromWKB and STAsBinary.

您可以通过局部的LINQ延伸到SQL实体类和添加自动转换特性使得这个过程多一点自动

You can make this process a bit more "automatic" by extending the partial Linq to SQL entity class and adding an auto-converting property:

public partial class Foo
{
    public SqlGeography Location
    {
        get { return SqlGeography.STGeomFromWKB(LocationData, 4326); }
        set { LocationData = value.STAsBinary(); }
    }
}

这假定 LocationData ​​ code>是计算 VARBINARY 列的名称;不包括真正的位置在你的LINQ to SQL定义列,你在上面的特设的方式加入。

This assumes that LocationData is the name of the computed varbinary column; you don't include the "real" Location column in your Linq to SQL definition, you add it in the ad-hoc fashion above.

还要注意的是,你将不能够做很多与此列比读取和写入它的其他;如果您尝试实际上它查询(即包括在一个其中, predicate),那么你只会得到一个类似引发NotSupportedException

Note also that you won't be able to do much with this column other than read and write to it; if you try to actually query on it (i.e. including it in a Where predicate) then you'll just get a similar NotSupportedException.