[英]Reading data from database gives Unable to cast object of type 'System.Byte' to type 'System.String' error
Please see the case 1 and 2 below. 请参阅下面的情况1和2。
In case 2 : reader.GetString(reader.GetOrdinal("dmic_only")) line return "1" successfully 在情况2中: reader.GetString(reader.GetOrdinal(“ dmic_only”))行成功返回“ 1”
In case 1 : same code part in string.IsNullOrEmpty( reader.GetString(reader.GetOrdinal("dmic_only")) ) == false throws exception. 在情况1中:string.IsNullOrEmpty( reader.GetString(reader.GetOrdinal(“ dmic_only”)) )== false会引发异常。
Exception : Unable to cast object of type 'System.Byte' to type 'System.String'. 异常:无法将类型为“ System.Byte”的对象转换为类型为“ System.String”。
dmic_only is a tinyint in database, not byte. dmic_only是数据库中的tinyint,而不是字节。 It is really interesting. 真的很有趣。 What is difference in cases? 大小写有什么区别?
Case 1: 情况1:
if ((!reader.IsDBNull(reader.GetOrdinal("dmic_disallowed"))
&& string.IsNullOrEmpty(reader.GetString(reader.GetOrdinal("dmic_disallowed"))) == false)
&& (!reader.IsDBNull(reader.GetOrdinal("dmic_only"))
&& string.IsNullOrEmpty(reader.GetString(reader.GetOrdinal("dmic_only"))) == false))
{
retVal.Add("dmic_disallowed", reader.GetString(reader.GetOrdinal("dmic_disallowed")));
retVal.Add("dmic_only", reader.GetString(reader.GetOrdinal("dmic_only")));
}
Case 2 : 情况2:
//if ((!reader.IsDBNull(reader.GetOrdinal("dmic_disallowed"))
//&& string.IsNullOrEmpty(reader.GetString(reader.GetOrdinal("dmic_disallowed"))) == false)
//&& (!reader.IsDBNull(reader.GetOrdinal("dmic_only"))
//&& string.IsNullOrEmpty(reader.GetString(reader.GetOrdinal("dmic_only"))) == false))
//{
retVal.Add("dmic_disallowed", reader.GetString(reader.GetOrdinal("dmic_disallowed")));
retVal.Add("dmic_only", reader.GetString(reader.GetOrdinal("dmic_only")));
//}
The exception you are getting is telling you exactly what you need to know... 您得到的例外是告诉您您需要知道的确切信息...
reader.GetString(reader.GetOrdinal("dmic_only")) // will throw an error
as you have said dmic_only
is a tinyint
正如您所说的dmic_only
是tinyint
if you really want it as a string, you will have to unbox it first as a byte then to a string 如果您确实希望将其作为字符串,则必须先将其拆开为字节,然后再解压缩为字符串
string strValue = Convert.ToString((byte)reader["dmic_only"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.