列表正在复制同一行

时间:2013-09-11 16:22:13

标签: c#

我正在尝试从SQL Server检索客户列表,问题是,列表只返回同一行的副本。我想过可能在我的datareader中添加一个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();
        }
    }

4 个答案:

答案 0 :(得分:8)

您需要将var customer = new Customer();移动到while循环中(否则,您只创建一个Customer实例,重复覆盖其属性,并多次添加同一个实例列表):

while (reader.Read())
{
    var customer = new Customer();
    // As before...

答案 1 :(得分:4)

您看到副本的原因是因为您不断向集合中添加对同一Customer实例的引用。当您更新while循环中的对象时,List中的每个引用也会更新。

相反,您应该在循环的每次迭代中创建一个新实例。

答案 2 :(得分:3)

试试这个:

        while (reader.Read())
        {
          var customer = new Customer();
            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);
        }

答案 3 :(得分:0)

我喜欢它,如下所示。

考虑......

为什么在你可能并不总是想要的时候建立一个列表?

SqlConnectionSqlCommandSqlDataReader实施IDisposable

为什么try-finallyusing更简单和等效时使用public IEnumerable<Customer> GetCustomers() { using (var connection = new SqlConnection( ConfigurationManager.ConnectionStrings["conn"].ConnectionString)); { using (var command = new SqlCommand { CommandText = "SELECT " + "cust_id, " + "cust_code, " + "cust_name, " + "cust_descr, " + "created_dt " + " FROM customer", Connection = connection }) { connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return new Customer { CustId = reader.GetInt32(0), CustCode = reader.GetString(1), CustName = reader.GetString(2), CustDescr = reader.GetString(3), CreatedDt = reader.GetDateTime(4) }; } } } } }

为什么不使用对象初始化器?

为什么在只需要5?

时返回所有列?

在必要之前不要打开连接。


var customers =  GetCustomers().ToList();

然后,如果你需要一个清单

{{1}}