I'm trying to get values from my database, it works when all columns have values. When a value is NULL
, it returns an error.
我正在尝试从我的数据库中获取值,它在所有列都有值时起作用。当值为NULL时,它将返回错误。
I've managed to find a way to handle with the strings but if there's an integer I don't know how to handle it. I've tried to find a solution but none has worked for me so far! Here's the code, any help would be highly appreciated.
我已经设法找到一种方法来处理字符串,但如果有一个整数我不知道如何处理它。我试图找到一个解决方案但到目前为止没有一个对我有用!这是代码,任何帮助将受到高度赞赏。
Thanks!
while (dr.Read())
{
coments comentsar = new coments
{
Id = (int)dr["Id"],
Name = (string)dr["Name"],
Likes = (int)dr["Likes"],
// Signature = dr["Signature"].ToString(),
Datetime = (DateTime)dr["Datetime"]
};
comen.Add(comentsar);
return comen;
}
2 个解决方案
#1
1
You can check for null value and if the value is not null assign the variable using ternary operator:
您可以检查空值,如果值不为null,则使用三元运算符分配变量:
Signature = dr["Signature"] != DBNull.Value ? (string)dr["Signature"] : "No value",
Likes = dr["Likes"] != DBNull.Value ? Convert.ToInt32(dr["Likes"]) : 0,
#2
0
You need to change your types to Nullable
types.
您需要将类型更改为Nullable类型。
Change (int)dr["Likes"]
to (int?)dr["Likes"]
and Datetime = (DateTime)dr["Datetime"]
to Datetime = (DateTime?)dr["Datetime"]
.
将(int)dr [“Likes”]更改为(int?)dr [“Likes”]和Datetime =(DateTime)dr [“Datetime”]到Datetime =(DateTime?)dr [“Datetime”]。
You will also need to update your model coments
to allow for nullable types.
您还需要更新模型coments以允许可以为空的类型。
Microsoft Nullable Types。
#1
1
You can check for null value and if the value is not null assign the variable using ternary operator:
您可以检查空值,如果值不为null,则使用三元运算符分配变量:
Signature = dr["Signature"] != DBNull.Value ? (string)dr["Signature"] : "No value",
Likes = dr["Likes"] != DBNull.Value ? Convert.ToInt32(dr["Likes"]) : 0,
#2
0
You need to change your types to Nullable
types.
您需要将类型更改为Nullable类型。
Change (int)dr["Likes"]
to (int?)dr["Likes"]
and Datetime = (DateTime)dr["Datetime"]
to Datetime = (DateTime?)dr["Datetime"]
.
将(int)dr [“Likes”]更改为(int?)dr [“Likes”]和Datetime =(DateTime)dr [“Datetime”]到Datetime =(DateTime?)dr [“Datetime”]。
You will also need to update your model coments
to allow for nullable types.
您还需要更新模型coments以允许可以为空的类型。
Microsoft Nullable Types。