cho*_*obo 2 c# ado.net design-patterns repository dto
我刚刚开始将所有我的ado.net代码从asp.net页面移动到repo并为每个表创建dto(手动),但现在我不知道将sqldatareader转换为我的列表的有效方法是什么dto对象?
例如,我的dto是Customer.
我正在使用webforms,我没有使用ORM.我想慢慢开始在那里工作.
通常,模式看起来像:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个简短的示例,说明如何使用数据读取器检索数据:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果表列可以为空,则reader.IsDBNull在检索数据之前进行检查.