'How do I retrieve data for an observable colleciton inside an object from SQL Server for WPF C#?
I have a DB with multiple tables. for example :
- Customer : CustID, FirstName, LastName
- Order : OrderID, CustID, OrderName, Quantity
I'm using SqlCommand and SqlDataReader in Visual Studio (WPF C#) to retrieve the data.
My Customer can have multiple order. If I use a simple SELECT like :
SELECT * FROM Customer c JOIN Order o ON c.CustID = o.CustID
I obviously get multiple line depending on how many orders the customer have.
In C#, I retrieve my customer data
private Customer GetCustomer(SqlDataReader dataReader){
return = new Customer(int CustId: dataReader.GetInt32(0),
string FirstName: dataReader.GetString(1),
string LastName: dataReader.String(2), OrderCollection Order: ???)
}
but I don't understand how to get each order inside the collection. Each line only has the information of one order, the next line has the customer information again. And I can't seem to figure out how to combine multiple.
I can only do one SQL query at the time or it starts over from the first line. I have multiple customers who have each multiple orders.
public override CustomersCollection GetCustomerDatas()
{
string sql = "SELECT * FROM Customer c JOIN Order o ON c.CustID = o.CustID";
SqlCommand cmd = new SqlCommand(sql, SqlConnection);
SqlDataReader dataReader = cmd.ExecuteReader();
CustomersCollection customers= new CustomersCollection();
while (dataReader.Read()){
Customer c = GetCustomer(dataReader);
if (c != null)
{
customers.Add(c);
}
}
dataReader.Close();
return customers;
}
Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
