How to convert sqldatareader to list of dto's?

旧时模样 提交于 2019-12-02 06:52:39

问题


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 convert a sqldatareader to a list of my dto objects?

For example sake, my dto is Customer.

I am using webforms and I am NOT using an ORM. I would like to start slow and work my way up there.


回答1:


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

var customers = new List<Customer>();
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.




回答2:


Usually the pattern looks something like:

List<Customer> list = new List<Customer>();

using(SqlDataReader rdr = GetReaderFromSomewhere()) {
  while(rdr.Read()) {
     Customer cust = new Customer();
     cust.Id = (int)rdr["Id"];
     list.Add(cust)
  }
}



回答3:


You defenitly should look at Massive - this simple wrapper over ADO.NET

var table = new Customer();
//grab all
var customers = table.All();
//just grab from customer 4. This uses named parameters
var customerFour = table.All(columns: "CustomerName as Name", where: "WHERE customerID=@0",args: 4);


来源:https://stackoverflow.com/questions/8249223/how-to-convert-sqldatareader-to-list-of-dtos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!