Cannot assign DBNull value to SqlParameter
When trying to assign a null value to SqlParameter, the following code will report an error:
<code class="language-csharp">SqlParameter[] parameters = new SqlParameter[1]; SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int); planIndexParameter.Value = (AgeItem.AgeIndex == null) ? DBNull.Value : AgeItem.AgeIndex; parameters[0] = planIndexParameter;</code>
The problem is that the ?: operator cannot determine the return type because it may be an int type value or a DBNull type value, and the two are incompatible.
Solution:
To solve this problem, you can choose the following methods:
<code class="language-csharp">SqlParameter[] parameters = new SqlParameter[1]; SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int); planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value; parameters[0] = planIndexParameter; </code>
<code class="language-csharp">SqlParameter[] parameters = new SqlParameter[1]; SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int); planIndexParameter.Value = AgeItem.AgeIndex ?? DBNull.Value; parameters[0] = planIndexParameter; </code>
According to the MSDN documentation for the ?: operator, first_expression and second_expression must be of the same type, or one type can be implicitly converted to the other.
The above is the detailed content of How to Handle DBNull Values When Assigning to SQL Parameters in C#?. For more information, please follow other related articles on the PHP Chinese website!