无法将对象从DBNull强制转换为其他类型

无法将对象从DBNull强制转换为其他类型。


我有一个以下函数抛出上述错误。我正在处理存储过程和C#代码中的所有空值。


那么它在哪里得到这个错误?


我可以在catch块中看到错误。但我不明白以下create()中哪一行得到错误。


public Boolean Create(DataTO DataTO)

{

    IDbTrans transaction = null;

    IDbCmd IDbCmd;


    string EncryptedPassword = Encrypt(DataTO.txtPwd);

    Base dataAccCom = null;


    try

    {

        dataAccCom = Factory.Create();

        dataAccCom.OpenConnection();

        transaction = dataAccCom.BeginTransaction();

        IDbCmd = dataAccCom.CreateCommand("sp_Register", true);

        dataAccCom.ExecuteNonQuery(IDbCmd);

        DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));

        transaction.Commit();

        return true;




    }

    catch (System.Exception ex)

    {

        if (transaction != null)

        {

            transaction.Rollback();

        }

        throw ex;

    }

    finally

    {

        transaction = null;

        if (dataAccCom != null)

        {

            dataAccCom.CloseConnection();

        }

        dataAccCom = null;

        IDbCmd = null;

    }

}


public string ReplaceNull(string value)

{

    if (value == null)

    {

        return "";

    }

    else

    {

        return value;

    }

}


public DateTime ReplaceNull(DateTime value)

{

    if (value == null)

    {

        return DateTime.Now;

    }

    else

    {

        return value;

    }

}


public double ReplaceNull(double value)

{

    if (value == null)

    {

        return 0.0;

    }

    else

    {

        return value;

    }

}


30秒到达战场
浏览 1080回答 3
3回答

qq_笑_17

错误原因:在面向对象的编程语言中,null表示缺少对对象的引用。DBNull表示未初始化的变体或不存在的数据库列。来源:MSDN我遇到的实际代码错误:在更改代码之前:    if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working     {            seqno  = 1;       }    else    {          seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;     }更改代码后:   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly        {                    seqno  = 1;          }            else            {                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;             }结论:当数据库值返回null值时,我们建议使用DBNull类,而不是像C#语言一样指定为null。
打开App,查看更多内容
随时随地看视频慕课网APP