如何SqlDataReader对象转换为DTO的名单? [英] How to convert sqldatareader to list of dto's?
问题描述
我刚开始从asp.net页面回购的创造DTO的为每个表(手动)将所有我的ado.net code,但现在我不知道什么是转换一个很好的有效的方法SqlDataReader的到我的DTO对象的列表?
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?
例如缘故,我的DTO是客户。
For example sake, my dto is Customer.
我使用WebForms和我不是使用ORM。我想开始缓慢和工作我的方式存在。
I am using webforms and I am NOT using an ORM. I would like to start slow and work my way up there.
推荐答案
在这里,你如何可以使用数据读取器检索数据很短的例子:
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);
}
}
}
}
如果一个表列可以为空,然后检查 reader.IsDBNull
之前检索数据。
If a table column is nullable then check reader.IsDBNull
before retrieving the data.
这篇关于如何SqlDataReader对象转换为DTO的名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!