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
Release: 2025-01-11 08:48:45
Original
972 people have browsed it

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>
Copy after login

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>
Copy after login
  • 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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template