Foreword:
When refactoring in the computer room today, I encountered this error: Object cannot be converted from DBnull to other types
What is DBNull?
DBNull is a separate type System.DBNull in DotNet. It has only one value DBNull.Value.
DBNull directly inherits Object, so DBNull is not a string, not an int, nor a DateTime
What does it mean that objects cannot be converted from DBnull to other types?
After Baidu, I know that this error is due to the NULL value in our database, and the NULL value of the database is represented by DBNULL.value in the code and cannot be converted to other types.
However, after my D layer found this null value from the database, I wanted to convert it to DateTime type data.
Solution:
1. Directly set the column in the database and cannot be empty.
2. First judge the obtained value, if it is a null value in the database, assign a value to it.
if(a == DBnull)
{
a = 1;
}
else
{
Convert.ToInt32(a);
}
3. Try/catch the obtained value
Brainstorming:
The difference between Int32 and Int64:
int32-value range: -2147483648 to 2147483647
int64-value range: -9223372036854775808 to 9223372036854775808