Is it possible to coalesce string and DBNull in C#?

前端 未结 10 1348
滥情空心
滥情空心 2021-01-02 06:24

I\'m writing a C# routine to call a stored proc. In the parameter list I\'m passing in, it is possible that one of the values can legally be null. So I thought I\'d use a

10条回答
  •  暖寄归人
    2021-01-02 06:45

    The Null Coalesce operator only with with data of the same type. You cannot send NULL to the SqlParamater as this will make Sql Server says that you didn't specify the parameter.

    You can use

    new SqlParameter("@theParam", (object)theParam ?? (object)DBNull.Value)
    

    Or you could create a function that return DBNull when null is found, like

    public static object GetDataValue(object o)
    {
        if (o == null || String.Empty.Equals(o))
            return DBNull.Value;
        else
            return o;
    }
    

    And then call

    new SqlParameter("@theParam", GetDataValue(theParam))
    

提交回复
热议问题