C# ASP.Net Parameters.AddWithValue rejecting null value for parameter

前端 未结 7 1745
臣服心动
臣服心动 2021-01-18 04:22

I am populating tables using a stored procedure. The table allows a \'null\' for the middle initial of the name, but I\'m getting the following error message:

7条回答
  •  迷失自我
    2021-01-18 04:54

    I created an extension method to battle this problem. Marcin's suggestion is also worth considering if you can update the stored procedure.

    cmd.Parameters.AddString("@MyParamName", myValue);
    
    
    public static class SQLExtension
    {
        public static void AddString(this SqlParameterCollection collection, string parameterName, string value)
        {
            collection.AddWithValue(parameterName, ((object)value) ?? DBNull.Value);
        }
    }
    

提交回复
热议问题