我正在尝试从 SQL Server 检索客户列表,问题是,该列表仅返回同一行的副本。我考虑过可能在我的数据阅读器中添加一个 foreach 循环,但我不确定如何实现它。任何帮助表示赞赏。
public IList<Customer> GetCustomers()
{
IList<Customer> customers = new List<Customer>();
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
conn.Open();
try
{
var command = new SqlCommand
{
CommandText = "SELECT * FROM customer",
Connection = conn
};
SqlDataReader reader = command.ExecuteReader();
var customer = new Customer();
while (reader.Read())
{
customer.CustId = (int) reader["cust_id"];
customer.CustCode = (string) reader["cust_code"];
customer.CustName = (string) reader["cust_name"];
customer.CustDescr = (string) reader["cust_descr"];
customer.CreatedDt = (DateTime) reader["created_dt"];
customers.Add(customer);
}
return customers;
}
finally
{
conn.Close();
conn.Dispose();
}
}