如何将List 添加到对象A,其中List 是类A的一部分

问题描述 投票:0回答:1

我有以下两类客户和产品。我正在从数据库获取数据,并将其读取到SqlDataReader中。因此,我必须将其阅读给Customer Object。我们将为每个客户提供多个产品。在这里,我必须将“产品”对象添加到“客户对象”(我们可能为每个客户提供多个产品。请提出任何建议..什么是最好的方法?

public class Customer
{
    public int CustomerId {get;set;}
    public string Name {get;set;}
    public List<Products> _products {get;set;}      
}

public class Products
{
    public int CustomerId {get;set;}
    public int ProductId {get;set;}
    public string Name {get;set;}
    public int Quantity {get;set;} 
}


While(dataReader.Read())
{
    var _customer = new Customer{
        CustomerId = (int)rdr["CustomerId"];
        Name = (string)rdr["CustomerName"];
        City    = (string)rdr["City"];
    };

    var _product = new Products
    {
        CustomerId = (int)rdr["CustomerId"];
        ProductId = (int)rdr["ProductId"];
        Name = (string)rdr["ProductName"];
        Quantity = (int)["Quantity"];
    };
}
c# sqldatareader
1个回答
-2
投票
public List<Customer> GetCustomers(SqlConnection conn) {
  using (conn);
  conn.Open();
  SqlCommand command = new SqlCommand("your_query;",connection);
  SqlDataReader reader = command.ExecuteReader();

  var customers = new List<Customer>();
  var products = new List<Product>();

  while (reader.Read()) {  
    var customerId = reader.GetInt32["CustomerId"];
    var customer = new Customer() {
      CustomerId = customerId,
      Name = reader.GetString["CustomerName"],
      City    = reader.GetString["City"]
    };
   customers.Add(customer);

    var product = new Products
    {
      CustomerId = customerId,
      ProductId = reader.GetInt32["ProductId"],
      Name = reader.GetString["ProductName"],
      Quantity = reader.GetInt32["Quantity"]
    };
    products.Add(product);
  }
  reader.Close();

   return customers.ForEach(item => {
     item.Products = products.Where(x => x.customerId == item.CustomerId).ToList();
    });
   }
}

How to use DataReader

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.