Home >Backend Development >C++ >How to Handle 'Object cannot be cast from DBNull to other types' Errors in C#?

How to Handle 'Object cannot be cast from DBNull to other types' Errors in C#?

DDD
DDDOriginal
2025-01-11 15:06:421076browse

How to Handle

Cannot convert object from DBNull to other type

Error description:

The error message "Unable to convert object from DBNull to other type" indicates that an attempt to convert a DBNull value (representing a null value in the database) to a non-nullable type (Int64 in this case) failed.

Error reason:

In the provided code, the following line attempts to convert the value of the output parameter named "op_Id" to an Int64:

<code>DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));</code>

If the stored procedure returns a DBNull value for this parameter, the conversion will fail with an error.

Solution:

To resolve this issue, explicitly check if the value of the output parameter is DBNull before attempting the conversion. If DBNull, null or the default value is assigned to the corresponding property in the DataTO object. Here is the updated code:

<code>var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");
if (outputParam != DBNull.Value)
    DataTO.Id = Convert.ToInt64(outputParam);
else
    DataTO.Id = null; // 或分配默认值,例如 0 或 -1</code>

This modification ensures that the code is robust when dealing with null values ​​that may exist in the database. Using outputParam != DBNull.Value is more concise and clear than !(outputParam is DBNull) and there is no significant difference in performance. The choice of setting DataTO.Id to null or a default value depends on your application logic and whether the type of the DataTO.Id attribute allows nulling.

The above is the detailed content of How to Handle 'Object cannot be cast from DBNull to other types' Errors 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