Search code examples
c#sql-servernullsqlparameter

How I can send null values in Geography SQL Server field if allow NULL, with SqlParameter and SQL Server Types SqlGeography in C#?


According to the following solution (https://stackoverflow.com/a/42976399/2825284):

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

My code:

SqlGeography geographyfield = null;
sqlParameter.ParameterName = "@geographyfield";
sqlParameter.UdtTypeName = "Geography";

if (geographyfield != null)
    sqlParameter.Value = geographyfield;
else
    sqlParameter.Value = DBNull.Value; // or null, I get the same error

How I can send null values in Geography field if allow NULL?

I get this error:

UdtTypeName property must be set only for UDT parameters.


Solution

  • According Jeroen Mostert's comment this is the solution: SqlGeography.Null.

    SqlGeography geographyfield = null;
    sqlParameter.ParameterName = "@geographyfield";
    sqlParameter.UdtTypeName = "Geography";
    
    if (geographyfield != null)
        sqlParameter.Value = geographyfield;
    else
        sqlParameter.Value = SqlGeography.Null;
    

    Thanks Jeroen Mostert.