在 Azure ASP.NET 网站中选择地理坐标时出错

Error selecting geography coordinate in Azure ASP.NET website

A​​zure 网站上的 ASP.net 网络表单从包含地理字段的 table 中进行选择。此字段导致错误 "DataReader.GetFieldType(0) returned null." 这是 SQL 创建 table 和来自 .ASPX.CS 文件的代码。

SQL 创建测试 Table [T]:

CREATE TABLE [dbo].[T](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [P] [geography] NULL,
 CONSTRAINT [PK_T] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

INSERT INTO T (P) VALUES (geography::Point(51.4618933852762, -0.926690306514502, 4326));

Test.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ConnectionStr = "Server=tcp:Server1,1433;Database=DB;User ID=User1;Password=Password1;Trusted_Connection=False;Encrypt=True;Connection Timeout=5;";
        SqlConnection Connection = new SqlConnection(ConnectionStr);
        Connection.Open();

        //string SQL = "SELECT CONVERT(VARBINARY(100), P) P FROM T";
        string SQL = "SELECT P FROM T";

        SqlDataAdapter da = new SqlDataAdapter(SQL, Connection);

        DataTable dt = new DataTable();

        da.Fill(dt);

        Connection.Close();
        Response.Write(dt.Rows[0]["P"].ToString());
    }
}

首先,您是否已将 SqlServerTypes 添加到您的项目中?这是您的项目 "understand" 地理数据类型所必需的。 更新:详细说明here

其次,如果您尝试从地理字段中检索 lat/long,则需要将其作为点进行查询:

SELECT P.Lat, P.Long FROM T

如果您必须使用 SqlServerTypes,请确保通过它的 NuGet 程序包 (https://www.nuget.org/packages/Microsoft.SqlServer.Types/) 将其引入您的解决方案,并注意它包括 32 位和 64 位版本,确保您使用的是与您在 Azure 中的网站使用的版本相同(说明可在包的 readme.htm 文件中找到)。

您可能还需要考虑以下内容,摘自 readme.htm:

Action required to load native assemblies

To deploy an application that uses spatial data types to a machine that does not have 'System CLR Types for SQL Server' installed you also need to deploy the native assembly SqlServerSpatial110.dll. Both x86 (32 bit) and x64 (64 bit) versions of this assembly have been added to your project under the SqlServerTypes\x86 and SqlServerTypes\x64 subdirectories. The native assembly msvcr100.dll is also included in case the C++ runtime is not installed.

You need to add code to load the correct one of these assemblies at runtime (depending on the current architecture).

ASP.NET applications For ASP.NET applications, add the following line of code to the Application_Start method in Global.asax.cs:

SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));

Desktop applications For desktop applications, add the following line of code to run before any spatial operations are performed:

SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);