使用SQL geography字段初始化.NET DbGeography对象

时间:2017-04-10 17:23:01

标签: c# sql .net sql-server entity-framework

使用DbGeography包中的Microsoft.SqlServer.Type类型来存储空间数据(只是点)的实体框架在MSSQL DB中显示如下:

0xE6100000010CAA00B9D75CA84740F4FDD478E926FA3F

如何格式化此十六进制字符串以及如何使用它来初始化新的DbGeography对象?

2 个答案:

答案 0 :(得分:4)

修改

我找到了一种将HEX字符串转换为DbGeography的方法,首先将其转换为SqlGeography类型SqlGeography

请务必添加对using Microsoft.SqlServer.Types;

的引用
    static void Main(string[] args)
    {
        //0xE6100000010C3D7D04FEF012414034B275BA3D4E5240
        var point = "E6100000010C3D7D04FEF012414034B275BA3D4E5240";

        var pointBytes =  Enumerable.Range(0, point.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(point.Substring(x, 2), 16))
                 .ToArray();


        var sqlbytes = new SqlBytes(pointBytes);


        var sqlPoint = SqlGeography.Deserialize(sqlbytes);

        Console.WriteLine("SqlGeography = {0} - {1}", sqlPoint.Lat, sqlPoint.Long);


        DbGeography newGeography = DbGeography.FromText(sqlPoint.ToString(), DbGeography.DefaultCoordinateSystemId);

        Console.WriteLine("EF DBGeography = {0} - {1}", newGeography.Latitude, newGeography.Longitude);


        Console.ReadKey();

    }

确认是正确的:

enter image description here

答案 1 :(得分:0)

MSSQL存储地理数据的格式在[MS-SSCLRT]: Microsoft SQL Server CLR Types Serialization Formats中定义。如the 5th revision中的3.1.2所示,格式如下:

0xE6100000010CAA00B9D75CA84740F4FDD478E926FA3F

SRID:                   E6 10 00 00                (4326, WGS84)
VERSION:                01 
SERIALIZATION PROPS:    0C
X (LONGITUDE):          AA 00 B9 D7 5C A8 47 40    (47.3153333333333)
Y (LATITUDE):           F4 FD D4 78 E9 26 FA 3F    (1.6345)

此数据可以转换为double,可用于初始化新的DbGeography实例。

var x = BitConverter.ToDouble(new byte[] { 
    0xAA, 0x00, 0xB9, 0xD7, 0x5C, 0xA8, 0x47, 0x40 }, 0);

var y = ...;

DbGeography.FromText($"POINT({x} {y})");