Home >Backend Development >C++ >How to Handle DBNull Values When Assigning to SQL Parameters in C#?

How to Handle DBNull Values When Assigning to SQL Parameters in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-11 08:48:45973browse

How to Handle DBNull Values When Assigning to SQL Parameters in C#?

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:

  • Casting: Casts the AgeIndex instance to type object, which satisfies the requirements of the ?: operator:
<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>
  • Use the null coalescing operator: Use the ?? null coalescing operator:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn