How can I save the data in an IEnumerable of the following code?

1

What I take care of is to save the data that that query returns to me in a list, to be able to execute it in a WCF calling that list, this is what I have tried:

public class ConexionSQL
    {
        public void DatosDB()
        {
            using (SqlConnection cnx = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Vi"].ToString()))
            {
                System.Data.SqlClient.SqlCommand cmd = new SqlCommand();
                SqlDataReader reader;
                cmd.Connection = cnx;
                cmd.CommandText = "SELECT * FROM dbo.Empleado";
                cmd.CommandType = CommandType.Text;
                cnx.Open();
                reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t\t{5}\t\t{6}", reader.GetName(0),
                        reader.GetName(1), reader.GetName(2), reader.GetName(3), reader.GetName(4), reader.GetName(5), reader.GetName(6));

                    while (reader.Read())
                    {
                        Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", reader.GetInt32(0),
                           reader.GetInt32(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(5), reader.GetString(6));
                    }
                }
                reader.Read();
            }
        }
    }

Could you please help me?

Greetings and good afternoon.

    
asked by Diego Rodriguez 08.05.2018 в 00:44
source

1 answer

2

First of all you need to define a class that has the seven fields or propoedades that you print, e.g.,

public class TestObject {
    public int PropertyOne { get; set; }
    public int PropertyTwo { get; set; }
    public string PropertyThree { get; set; }
    public string PropertyFour { get; set; }
    public string PropertyFive { get; set; }
    public string PropertySix { get; set; }
    public string PropertySeven { get; set; }
}

After the while cycle, you need to define a list of that class:

var objects = new List<TestObject>();

Finally in the whie cycle you need to add the following sentence:

objects.Add(new TestObject()
{
    PropertyOne = reader.GetInt32(0),
    PropertyTwo = reader.GetInt32(1),
    PropertyThree = reader.GetString(2),
    PropertyFour = reader.GetString(3),
    PropertyFive = reader.GetString(4),
    PropertySix = reader.GetString(5),
    PropertySeven = reader.GetString(6)
});

That way in each iteration you are going to add an object and each object corresponds to a record of your query.

    
answered by 08.05.2018 / 01:22
source