mkul
mkul

Reputation: 811

Save geography type to SQL Server

My table has column with 'geography' type. How I can save data to this table with C# SqlGeography.Point() and ado.net? I have following code

var stringPos = item.Position.Split(',');
var latPos = double.Parse(stringPos[0], CultureInfo.InvariantCulture);
var longPos = double.Parse(stringPos[1], CultureInfo.InvariantCulture);

var position = SqlGeography.Point(latPos, longPos, 4326);

string query = @"INSERT INTO myTable VALUES (@position, @postCode)";

SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@position", position);
cmd.Parameters.AddWithValue("@postCode", item.ZipCode);

cmd.ExecuteNonQuery();

I have following code but it throws exception:

UdtTypeName property must be set for UDT parameters.

Upvotes: 3

Views: 1762

Answers (1)

mkul
mkul

Reputation: 811

Solution:

Change

cmd.Parameters.AddWithValue("@position", position);

To

cmd.Parameters.Add(new SqlParameter("@position", position) { UdtTypeName = "Geography" });

Upvotes: 3

Related Questions