有没有办法将存储过程的结果映射到通用列表而不是数据集/数据表?
目前我遵循以下步骤:
- 执行存储过程
- 将结果放入数据集中
- 从数据集中填充列表。
有没有办法去掉第(2)步。
OleDbCommand cm = new OleDbCommand();
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
OleDbDataAdapter adp = new OleDbDataAdapter(cm);
DataTable dt = new DataTable();
adp.Fill(dt);
List<tblContacts> LstFile = new List<tblContacts>();
if (dt.Rows.Count > 0)
{
tblContacts t;
foreach (DataRow dr in dt.Rows)
{
t = PopulateContacts(dr);
LstFile.Add(t);
}
}
最佳答案
是的,您当然可以这样做 - 只需执行您的命令并返回一个读取器,然后遍历结果集中的行并构建您的对象:
using (OleDbCommand cm = new OleDbCommand())
{
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
List<tblContacts> LstFile = new List<tblContacts>();
using (OleDbReader reader = cm.ExecuteReader())
{
while(reader.Read())
{
tblContacts contact = new tblContacts();
// here, set the properties based on your columns from the database
contact.FirstName = reader.GetString(0);
contact.LastName = reader.GetString(1);
// etc.
LstFile.Add(contact);
}
reader.Close();
}
return LstFile;
}
有关 OleDbReader
及其使用方法的详细信息,see this other SO question或者使用 Bing 或 Google 在线查找大量教程和示例。
关于c# - 将存储过程结果填充到 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448149/