How to convert a DataSet to Int32?

1

I'm having a problem converting an information that is coming from my database to a variable of type Int32 .

When I do the select max(cur_id) from tbl_curriculo; I send the id information straight to a Dataset which I call ds .

I have my persistence return this ds and turn it into int so I can send this id to another table that will receive that id as foreign key, however I do not know how to do the conversion correctly .

When I pass the command Convert.toInt32() the IDE accuses that everything is ok, but at the time I send the code I get the following error

  

Invalid Cast Exception was unhandled by user code   An exception of type 'System.InvalidCastException' occurred in mscorlib.dll but was not handled in user code   Additional information: Can not convert an object of type 'System.Data.DataSet' to type 'System.IConvertible'.

I know the conversion is not working that way, and I also tried to pass the dataset without doing the conversion to see if it worked and it did not work either.

Below is my code for the page where the conversion is being done

protected void btn_Confirmar_Click(object sender, EventArgs e)
    {
        CurriculoDB.InsertCurriculo(Persistencia.Cu[0]);

        int id = Convert.ToInt32(CurriculoDB.SelectCur_Id());

        CandidatoDB.InsertCandidato(Persistencia.Cand[0], Persistencia.En[0], id);

        Persistencia.Cand.Clear();
        Persistencia.Curf.Clear();
        Persistencia.Cur.Clear();
        Persistencia.Expt.Clear();
        Persistencia.Contato.Clear();

        Response.Redirect("ConfirmacaoCandidato.aspx");
    }

Below the code for select

public static DataSet SelectCur_Id()
    {
        DataSet ds = new DataSet();
        IDbConnection objConnection;
        IDbCommand objCommand;
        IDataAdapter objDataAdapter;
        objConnection = Mapped.Connection();
        objCommand = Mapped.Command("select max(cur_id) from tbl_curriculo", objConnection);
        objDataAdapter = Mapped.Adapter(objCommand);

        objDataAdapter.Fill(ds); // O objeto DataAdapter vai preencher o 
        //  DataSet com os dados do BD, O método Fill é o responsável por   preencher o DataSet
        objConnection.Close();
        objCommand.Dispose();
        objConnection.Dispose();
        return ds;        
    }

Below the code of the table where the insert will be done

public static int InsertCandidato(Candidato can, Endereco end, int id)
    {
        int retorno = 0;
        try
        {
            IDbConnection conexao;
            IDbCommand comando;
            string sql = "insert into tbl_candidato values(0, ?can_nome, ?can_data_nascimento, ?can_sexo, ?can_cpf, ?can_cep, ?can_rua, ?can_bairro, ?can_cidade, ?can_estado, ?can_numero, ?can_complemento, ?fk_tbl_candidato_cur_id);";
            conexao = Mapped.Connection();
            comando = Mapped.Command(sql, conexao);
            comando.Parameters.Add(Mapped.Parameter("?can_nome", can.Nome_candidato));
            comando.Parameters.Add(Mapped.Parameter("?can_data_nascimento", can.Data_nascimento));
            comando.Parameters.Add(Mapped.Parameter("?can_sexo", can.Sexo));
            comando.Parameters.Add(Mapped.Parameter("?can_cpf", can.Cpf));
            comando.Parameters.Add(Mapped.Parameter("?can_cep", end.Cep));
            comando.Parameters.Add(Mapped.Parameter("?can_rua", end.Rua));
            comando.Parameters.Add(Mapped.Parameter("?can_bairro", end.Bairro));
            comando.Parameters.Add(Mapped.Parameter("?can_cidade", end.Cidade));
            comando.Parameters.Add(Mapped.Parameter("?can_estado", end.Estado));
            comando.Parameters.Add(Mapped.Parameter("?can_numero", end.Numero));
            comando.Parameters.Add(Mapped.Parameter("?can_complemento", end.Complemento));
            comando.Parameters.Add(Mapped.Parameter("?fk_tbl_candidato_cur_id", id));
            comando.ExecuteNonQuery();
            conexao.Close();
            comando.Dispose();
            conexao.Dispose();
        }
        catch (Exception)
        {
            retorno = -2;
        }
        return retorno;
    }
    
asked by anonymous 18.06.2016 / 07:07

2 answers

2

I'll start with three observations that do not go straight to the problem (I could even talk about other things).

I do not understand why people are opening and closing connections all the time inside the application. This is unnecessary most of the time and great for creating confusion. The amount of repetitive code there is impressive and this should spread throughout the application. I recommend understanding DRY . Of course not to do this you have to think about an appropriate architecture, but the tip is.

You should avoid calling Close() and Dispose() manually. If there is an exception, everything is open. It's best to use using . References: Is it correct to use a using block within another using block? , Method to execute when you destroy a class instance , Closing requisitions , Can an exception cause the closing of a SqlConnection? .

Capturing Exception is usually not legal, even more so to do what is being done in that code. I talk a lot about the misuse of exceptions , but I've noticed that it's rare that anyone wants to learn to do it right.

Your main problem

Why create a dataset if the only information you need is id ? Would not it be simpler to do something like this?

var valorParaRetornar = (int)Mapped.Command("select max(cur_id) from tbl_curriculo", objConnection).ExecuteScalar();

I am considering that this Mapped , which I do not know what it is, does what it should. Obviously the return of this method will already be int and will not require any conversion. This method could probably have 2 or 3 lines. In fact 1 up is enough if it is well-engineered (eliminate connection opening everywhere).

You can get the id already in the insert if you run a select last_insert_id(); together. Or get the LastInsertedId property of the MySQL command for .Net.

    
18.06.2016 / 13:51
1

Make a cast.

int id = (int) CurriculoDB.SelectCur_Id();

The cast should only be used if you are sure that the result of the call will correspond to the object or value. That is you have to make sure the call:

CurriculoDB.SelectCurt_Id();

will return an int. In case a Long or another type of this long return has suffered loss of content. Example:

long id = 1000000000000000;
int idComValorPerdido = (int) id;
Console.WriteLine(idComValorPerdido); // 1000000000

Notice that you hear loss

    
18.06.2016 / 13:04