猿问

对象不能从 DBNull 转换为 C# 中的其他类型异常

我正在使用 MySql 数据库,如果我执行解决方案,我会在 catch 块中收到异常,下面是我的代码


MySqlManager dac = new MySqlManager();

long value = 0;

DbCommand dbCommand = dac.GetStoredProcCommand("Spforgotpassword");

dac.AddOutParameter(dbCommand, "p_op_EmailId", DbType.Int32, -1);

dac.AddInParameter(dbCommand, "p_p_EmailId", DbType.String, data.Email_Id);

dac.AddInParameter(dbCommand, "p_p_Password", DbType.String, Generatehash256(data.Password));

dac.AddInParameter(dbCommand, "p_P_EncryptedPassword", DbType.String, Encryption.Encrypt(data.Password));

dac.AddInParameter(dbCommand, "p_P_Mode", DbType.String, 102);

dac.AddInParameter(dbCommand, "p_IPAddress", DbType.String, data.IPAddress);

IDataReader reader = dac.ExecuteReader(dbCommand);

if (reader.Read())

{

    value = reader["result"] == DBNull.Value ? default(long) : Convert.ToInt32(reader["result"]);

}

dac.CloseConnection(dbCommand, reader);

if (Convert.ToBoolean(ConfigurationSettings.AppSettings["EnableEmail"]))

{

    if (Convert.ToInt32(dac.GetParameterValue(dbCommand, "p_op_EmailId")) != -1)

    {

        Mail.WebMail oWebmail = new Mail.WebMail(dac.GetParameterValue(dbCommand, "p_op_EmailId").ToString());


    }

}

return value;

一旦我执行这一行,我就会收到异常 --- Object cannot be cast from DBNull to other types


dac.GetParameterValue(dbCommand, "p_op_EmailId")

该p_op_EmailId是输出参数。


芜湖不芜
浏览 437回答 1
1回答

白衣非少年

看起来存储过程将值设置为p_op_EmailIdto null。所以你不能Int32直接将它转换为。相反,您可以将其转换为一个可为空的 int,并-1在比较之前将其合并:(dac.GetParameterValue(dbCommand, "p_op_EmailId") as int? ?? -1) != -1
随时随地看视频慕课网APP
我要回答