所以,下面的代码给了我一个相当令人困惑的例外。
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对象的列中。
答案 0 :(得分: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();
答案 1 :(得分:1)
然而这个问题已经过时了,但这个答案可以帮助未来的用户:
我发现不匹配是因为不同的SqlGeography类版本。通过使用正确版本的Microsoft.SqlServer.Types.dll程序集可以解决此问题。
对于使用.net 4的应用程序,我将dll更改为2009.100版本(适用于SQL Server 2008R2 SDK),但是我连接到SQL Server 2014。