Set a database value to null with a SqlCommand + parameters

前端 未结 3 1180
情书的邮戳
情书的邮戳 2020-12-15 03:27

I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).

Using parameters with values are fine, but when I try to set a fie

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 04:05

    I use a SqlParameterCollection extension method that allows me to add a parameter with a nullable value. It takes care of converting null to DBNull. (Sorry, I'm not fluent in VB.)

    public static class ExtensionMethods
    {
        public static SqlParameter AddWithNullable(this SqlParameterCollection parms,
                string parameterName, T? nullable) where T : struct
        {
            if (nullable.HasValue)
                return parms.AddWithValue(parameterName, nullable.Value);
            else
                return parms.AddWithValue(parameterName, DBNull.Value);
        }
    }
    

    Usage:

    string? optionalName = "Bozo";
    cmd.Parameters.AddWithNullable("@Name", optionalName);
    

提交回复
热议问题