簡體   English   中英

使用SqlGeography和C#的DataTable值不匹配

[英]DataTable Value Mismatch Using SqlGeography and C#

所以,下面的代碼給了我一個相當混亂的例外。

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對象的列中。

嘗試直接插入

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(); 

但是這個問題已經很久了,但這個答案可以幫助未來的用戶
我發現不匹配是因為不同的SqlGeography類版本。 通過使用正確版本的Microsoft.SqlServer.Types.dll程序集可以解決此問題。
對於使用.net 4的應用程序,我將dll更改為2009.100版本(適用於SQL Server 2008R2 SDK),但我連接到SQL Server 2014。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM