How to convert sqldatareader to list of dto's?

前端 未结 3 1290
北荒
北荒 2021-01-22 03:28

I just started moving all my ado.net code from the asp.net pages to repo\'s and created dto\'s for each table (manually), but now I don\'t know what is a good efficient way to c

3条回答
  •  太阳男子
    2021-01-22 04:11

    Here a short example on how you can retrieve your data using a data reader:

    var customers = new List();
    string sql = "SELECT * FROM customers";
    using (var cnn = new SqlConnection("Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;")) {
        cnn.Open();
        using (var cmd = new SqlCommand(sql, cnn)) {
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                // Get ordinals (column indexes) from the customers table
                int custIdOrdinal = reader.GetOrdinal("CustomerID");
                int nameOrdinal = reader.GetOrdinal("Name");
                int imageOrdinal = reader.GetOrdinal("Image");
                while (reader.Read()) {
                    var customer = new Customer();
                    customer.CustomerID = reader.GetInt32(custIdOrdinal);
                    customer.Name = reader.IsDBNull(nameOrdinal) ? null : reader.GetString(nameOrdinal);
                    if (!reader.IsDBNull(imageOrdinal)) {
                        var bytes = reader.GetSqlBytes(imageOrdinal);
                        customer.Image = bytes.Buffer;
                    }
                    customers.Add(customer);
                }
            }
        }
    }
    

    If a table column is nullable then check reader.IsDBNull before retrieving the data.

提交回复
热议问题