c# – Object cannot be cast from DBNull to other types
c# – Object cannot be cast from DBNull to other types
Im thinking that your output parameter is coming back with a DBNull value. Add a check for that like this
var outputParam = dataAccCom.GetParameterValue(IDbCmd, op_Id);
if(!(outputParam is DBNull))
DataTO.Id = Convert.ToInt64(outputParam);
I suspect that the line
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, op_Id));
is causing the problem. Is it possible that the op_Id
value is being set to null by the stored procedure?
To Guard against it use the Convert.IsDBNull
method. For example:
if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, op_Id))
{
DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, op_Id));
}
else
{
DataTO.Id = ...some default value or perform some error case management
}
c# – Object cannot be cast from DBNull to other types
You need to check for DBNull
, not null
. Additionally, two of your three ReplaceNull
methods dont make sense. double
and DateTime
are non-nullable, so checking them for null
will always be false
…