1

所以,下面的代码给了我一个相当混乱的异常。

public void BuildTable()
        {
            using (SqlConnection connection = new SqlConnection("Data Source=ylkx1ic1so.database.windows.net;Initial Catalog=hackathon;Persist Security Info=True;User ID=REDACTED;Password=REDACTED"))
            {
                SqlGeographyBuilder builder = createTestPoint();            
                SqlGeography myGeography = builder.ConstructedGeography;
                connection.Open();
                DataTable myTable = new DataTable();
                using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM myTable", connection))
                {
                    SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
                    adapter.Fill(myTable);
                    myTable.Rows.Add(6, "Test", myGeography);
                    adapter.Update(myTable);
                }
            }
        }

        private SqlGeographyBuilder createTestPoint()
        {
            SqlGeographyBuilder builder = new SqlGeographyBuilder();
            builder.SetSrid(4326);
            builder.BeginGeography(OpenGisGeographyType.Point);
            builder.BeginFigure(31, -85);
            builder.EndFigure();
            builder.EndGeography();
            return builder;
        }

myTable.Rows.Add(6, "Test", myGeography); 是我得到以下异常的地方:

Type of value has a mismatch with column typeCouldn't store <POINT (-85 31)> in placemark Column.  Expected type is SqlGeography.

我不明白为什么这会失败。在调试时我尝试了这个:

for (int i = 0; i < myTable.Columns.Count; i++)
                    {
                        Debug.WriteLine(myTable.Columns[i].DataType);
                    }
                    Debug.WriteLine(myGeography.GetType());

我的输出是:

System.Int32
System.String
Microsoft.SqlServer.Types.SqlGeography
Microsoft.SqlServer.Types.SqlGeography

因此,我肯定会尝试将 SqlGeography 对象放在一个采用 SqlGeography 对象的列中。

4

2 回答 2

2

尝试直接插入

string sqlCommandText = "insert into myTable(col1,col2,col3) Values(@col1,@col2,@col3)";
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, connection);
sqlCommand.Parameters.AddWithValue("@col1", 6);
sqlCommand.Parameters.AddWithValue("@col2", "Test");
sqlCommand.Parameters.Add(new SqlParameter("@col3", myGeography) { UdtTypeName = "Geography" });
sqlCommand.ExecuteNonQuery(); 
于 2013-06-02T13:27:46.547 回答
1

然而这个问题很老,但这个答案可以帮助未来的用户:
我发现不匹配是因为不同的 SqlGeography 类版本。该问题可以通过使用正确版本的 Microsoft.SqlServer.Types.dll 程序集来解决。
我将 .net 4 的应用程序的 dll 更改为 2009.100 版本(用于 SQL Server 2008R2 SDK),但是我正在连接到 SQL Server 2014。

于 2015-07-27T11:55:01.007 回答