Pergunta

I have worked on retrieving the data from SQL database using Datareader and populate it in Datatable.. But, I am wondering whether is there any way to handle the data from datareader without using datatable ? I mean- handling the table values using Objects should be more preferable..

But, I dont want to use LINQ here since, I am going to use ADOMD object to pull the data from database(Cubes)..

Foi útil?

Solução

Have a look at dapper-dot-net. I'm not sure how it works with ADOMD.NET, but it does neatly materialise query results in dynamic objects.

Outras dicas

Just loop thrugh the items and set it as the property values of your custom class. The below example read data from Customer table and Create a List of Customer Class object. Assuming you have a Customer POCO with ID and Name as Properties

List<Customer> custList= new List<Customer>();
string connString="yourConnectionStringHere";
using (var conn = new SqlConnection(connString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT ID,NAME From Customer";           

        using (var reader = cmd.ExecuteReader())
        {
           if (reader.HasRows)
           {  
             while (reader.Read())
             {
               var cust= new Customer();

                    if (!reader.IsDBNull( reader.GetOrdinal("ID")))
                        cust.ID = reader.GetInt32(reader.GetOrdinal("ID"));

                    if (!reader.IsDBNull( reader.GetOrdinal("Name")))
                        cust.Name = reader.GetString(reader.GetOrdinal("Name"));

                    custList.Add(cust);
             }
           }
        }
    }
}

public List GetEmployee(string spname) {

        con.Open();
        cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        reader = cmd.ExecuteReader();
        List<EmployeeDetails> lstemp = new List<EmployeeDetails>();
        while (reader.Read())
        {
            EmployeeDetails emp = new EmployeeDetails();
            emp.EmployeeId =Convert.ToInt32( reader["EmployeeId"].ToString());
            emp.FirstName = reader["FirstName"].ToString();
            emp.LastName = reader["LastName"].ToString();
            emp.DOB = Convert.ToDateTime(reader["DOB"].ToString());
            emp.Gender = Convert.ToInt32(reader["Gender"].ToString());
            emp.QName = reader["QName"].ToString();
            emp.Dname = reader["DName"].ToString();
            emp.Email = reader["Email"].ToString();



            lstemp.Add(emp);

        }


        return lstemp;
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top