Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save geography type to SQL Server

Tags:

c#

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.

like image 313
mkul Avatar asked Aug 03 '26 23:08

mkul


1 Answers

Solution:

Change

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

To

cmd.Parameters.Add(new SqlParameter("@position", position) { UdtTypeName = "Geography" });
like image 80
mkul Avatar answered Aug 05 '26 12:08

mkul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!