Home >Backend Development >C++ >How to Handle 'Object cannot be cast from DBNull to other types' Errors in C#?
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!