65.9K
CodeProject is changing. Read more.
Home

TIP: Managing SqlGeography class from C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

May 29, 2010

CPOL
viewsIcon

20320

How to Insert or Update an SqlGeography object in SQL Server 2008 from a C# application

It took me some time to get this to work. The problem is that SqlGeography C# type, which corresponds to Geography SQL type, is considered an user-defined type (UDT) by the .net SQL library. So, the proper way to insert or update a Geography field is something like this:
SqlGeography geo = // Get the coordinates from somewhere...

using (SqlCommand command = 
    new SqlCommand(@"UPDATE Points SET Point=@Point WHERE FeatureID='9999'", connection))
    command.Parameters.Add(new SqlParameter("@Point", geo) { UdtTypeName = "Geography" });
    command.ExecuteNonQuery();
}