Search code examples
c#sqlgeography

DataTable Value Mismatch Using SqlGeography and C#


So, the following code is giving me a rather confusing exception.

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;
        }

The line myTable.Rows.Add(6, "Test", myGeography); is where I"m getting the following exception:

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

What I don't get is why this would be failing. While debugging I tried this:

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

And my out put was:

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

So, I'm definitely trying to put a SqlGeography object in a column that takes SqlGeography objects.


Solution

  • try with direct insert

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