How to query a sqlserver table with (numeric) to c #

0

I have a problem and I am trying to make a query from c # to sqlserver but I get the following error

  

System.InvalidCastException: 'Unable to convert an object of type   'System.Decimal' to the type 'System.String'

And I know that the error seems to be that I have a column named "Age" of type numeric and when doing the query in c # taking it as String gives me the error, the big question would be, How could I call it correctly so I can run correctly.

        //Consulta 
    public static List<Estudiante> BuscarEstudiante(String pcedula)
    {
        List<Estudiante> Lista = new List<Estudiante>();
        using (SqlConnection conexion = BDcomun.ObtenerCOnexion())
        {
            SqlCommand comando = new SqlCommand(string.Format(                         //Cambie el 1 por el 0
                "Select nombre, cedula, correo, edad from Estudiante where cedula like '%{0}%'", pcedula), conexion);
            SqlDataReader reader = comando.ExecuteReader();

            while (reader.Read())
            {
                Estudiante pEstudiante = new Estudiante();
                pEstudiante.nombre = reader.GetString(0);
                pEstudiante.cedula = reader.GetString(1);
                pEstudiante.correo = reader.GetString(2);
                pEstudiante.edad   = reader.GetString(3);

                Lista.Add(pEstudiante);
            }
            conexion.Close();
            return Lista;
            //Fin consulta

The error I think comes from just

  

pEstudiante.edad = reader. GetString (3);

    
asked by Victor Escalona 19.03.2018 в 04:21
source

1 answer

2

You need to convert the data type to type string since reader returns a type System.Decimal , if your class Estudiante accepts strings, a simple conversion is enough using:

pEstudiante.edad = reader.GetDecimal(3).ToString();
    
answered by 19.03.2018 / 04:41
source