0

I am trying to get List of myModel from DataTable. It can be assured that myModel matches the fields in DataTable.

For example, DataTable as follow:

Name  id
Trump  1
Obama  0

myModel as follow:

class user{
    public string name { get; set; }
    public long id{ get; set; }
}

I know how to get List of DataRow by using DataAdapter. But still i will need to manually transform values in datarow to myModel column by column.

Now, I can only get List of myModel manually from dataReader, which is silly.

public List<user> get_users(string user_name)
{
    var user_list = new List<user>();
    using (SqlConnection connection = new SqlConnection(connStr))
    {
        connection.Open();
        using (SqlCommand cmd = new SqlCommand("exec select_user @name='" + + "'", connection))
        {
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                user_list.Add(new user()
                {
                    id = Convert.ToInt64(reader["id"]),
                    name = Convert.ToString(reader["name"]),
                });
            }
        }
        connection.Close();
    }
    return user_list;
}
gggpps
  • 151
  • 1
  • 6

1 Answers1

0

You either do it manually, or you use an object relational mapping technology like Microsoft's Entity Framework or another one like NHibernate.

rory.ap
  • 34,009
  • 10
  • 83
  • 174