Udostępnij za pośrednictwem


Nawigowanie po usłudze DataRelations

Jedną z podstawowych funkcji elementu DataRelation jest umożliwienie nawigacji z DataTable do innego DataTable w obiekcie . Umożliwia to pobranie wszystkich powiązanych DataRow obiektów w jednej tabeli DataTable w przypadku pojedynczego elementu DataRow z powiązanej tabeli DataTable. Na przykład po ustanowieniu elementu DataRelation między tabelą klientów i tabelą zamówień można pobrać wszystkie wiersze zamówienia dla określonego wiersza klienta przy użyciu polecenia GetChildRows.

Poniższy przykład kodu tworzy tabelę DataRelation między tabelą Customers a tabelą Orders (Zamówienia ) zestawu danych i zwraca wszystkie zamówienia dla każdego klienta.

DataRelation customerOrdersRelation =
    customerOrders.Relations.Add("CustOrders",
    customerOrders.Tables["Customers"].Columns["CustomerID"],
    customerOrders.Tables["Orders"].Columns["CustomerID"]);

foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
{
    Console.WriteLine(custRow["CustomerID"].ToString());

    foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
    {
        Console.WriteLine(orderRow["OrderID"].ToString());
    }
}
Dim customerOrdersRelation As DataRelation = _
   customerOrders.Relations.Add("CustOrders", _
   customerOrders.Tables("Customers").Columns("CustomerID"), _
   customerOrders.Tables("Orders").Columns("CustomerID"))

Dim custRow, orderRow As DataRow

For Each custRow In customerOrders.Tables("Customers").Rows
    Console.WriteLine("Customer ID:" & custRow("CustomerID").ToString())

    For Each orderRow In custRow.GetChildRows(customerOrdersRelation)
        Console.WriteLine(orderRow("OrderID").ToString())
    Next
Next

Kolejny przykład opiera się na poprzednim, łącząc cztery tabele i nawigując po relacjach między nimi. Podobnie jak w poprzednim przykładzie, CustomerID wiąże tabelę Customers z tabelą Orders (Zamówienia). Dla każdego klienta w tabeli Customers zostają określone wszystkie wiersze podrzędne w tabeli Orders, aby zwrócić liczbę zamówień określonego klienta oraz ich rzeczywiste wartości OrderID.

Rozszerzony przykład zwraca również wartości z tabel OrderDetails i Products . Tabela Orders (Zamówienia) jest powiązana z tabelą OrderDetails przy użyciu identyfikatora OrderID , aby określić, jakie produkty i ilości zostały zamówione dla każdego zamówienia klienta. Ponieważ tabela OrderDetails zawiera tylko ProductID zamówionego produktu, OrderDetails jest powiązana z Products poprzez ProductID w celu zwrócenia ProductName. W tej relacji tabela Products jest elementem nadrzędnym, a tabela Order Details jest elementem podrzędnym. W związku z tym podczas iteracji za pośrednictwem tabeli OrderDetails wywoływana jest funkcja GetParentRow w celu pobrania powiązanej wartości ProductName .

Zwróć uwagę, że po utworzeniu tabeli DataRelation dla tabel Customers and Orders żadna wartość nie jest określona dla flagi createConstraints (wartość domyślna to true). Zakłada się, że wszystkie wiersze w tabeli Orders mają wartość CustomerID, która istnieje w nadrzędnej tabeli Customers. Jeśli identyfikator CustomerID istnieje w tabeli Orders (Zamówienia), a nie istnieje w tabeli Customers (Klienci), spowoduje to zgłoszenie ForeignKeyConstraint wyjątku.

Jeśli kolumna podrzędna może zawierać wartości, których kolumna nadrzędna nie zawiera, ustaw flagę createConstraints na false podczas dodawania elementu DataRelation. W tym przykładzie flaga createConstraints jest ustawiona na false dla relacji danych między tabelą Orders a tabelą OrderDetails. Dzięki temu aplikacja zwraca wszystkie rekordy z tabeli OrderDetails i tylko podzestaw rekordów z tabeli Orders bez generowania wyjątku czasu wykonywania. Rozwinięty przykład generuje dane wyjściowe w następującym formacie.

Customer ID: NORTS  
  Order ID: 10517  
        Order Date: 4/24/1997 12:00:00 AM  
           Product: Filo Mix  
          Quantity: 6  
           Product: Raclette Courdavault  
          Quantity: 4  
           Product: Outback Lager  
          Quantity: 6  
  Order ID: 11057  
        Order Date: 4/29/1998 12:00:00 AM  
           Product: Outback Lager  
          Quantity: 3  

Poniższy przykład kodu to rozwinięty przykład, w którym zwracane są wartości z tabel OrderDetails i Products , z tylko podzbiorem rekordów w zwracanej tabeli Orders .

DataRelation customerOrdersRelation =
    customerOrders.Relations.Add("CustOrders",
    customerOrders.Tables["Customers"].Columns["CustomerID"],
    customerOrders.Tables["Orders"].Columns["CustomerID"]);

DataRelation orderDetailRelation =
    customerOrders.Relations.Add("OrderDetail",
    customerOrders.Tables["Orders"].Columns["OrderID"],
    customerOrders.Tables["OrderDetails"].Columns["OrderID"], false);

DataRelation orderProductRelation =
    customerOrders.Relations.Add("OrderProducts",
    customerOrders.Tables["Products"].Columns["ProductID"],
    customerOrders.Tables["OrderDetails"].Columns["ProductID"]);

foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
{
    Console.WriteLine("Customer ID: " + custRow["CustomerID"]);

    foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
    {
        Console.WriteLine("  Order ID: " + orderRow["OrderID"]);
        Console.WriteLine("\tOrder Date: " + orderRow["OrderDate"]);

        foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRelation))
        {
            Console.WriteLine("\t Product: " +
                detailRow.GetParentRow(orderProductRelation)["ProductName"]);
            Console.WriteLine("\t Quantity: " + detailRow["Quantity"]);
        }
    }
}
Dim customerOrdersRelation As DataRelation = _
   customerOrders.Relations.Add("CustOrders", _
   customerOrders.Tables("Customers").Columns("CustomerID"), _
   customerOrders.Tables("Orders").Columns("CustomerID"))

Dim orderDetailRelation As DataRelation = _
   customerOrders.Relations.Add("OrderDetail", _
   customerOrders.Tables("Orders").Columns("OrderID"), _
   customerOrders.Tables("OrderDetails").Columns("OrderID"), False)

Dim orderProductRelation As DataRelation = _
   customerOrders.Relations.Add("OrderProducts", _
   customerOrders.Tables("Products").Columns("ProductID"), _
   customerOrders.Tables("OrderDetails").Columns("ProductID"))

Dim custRow, orderRow, detailRow As DataRow

For Each custRow In customerOrders.Tables("Customers").Rows
    Console.WriteLine("Customer ID:" & custRow("CustomerID").ToString())

    For Each orderRow In custRow.GetChildRows(customerOrdersRelation)
        Console.WriteLine("  Order ID: " & orderRow("OrderID").ToString())
        Console.WriteLine(vbTab & "Order Date: " & _
          orderRow("OrderDate").ToString())

        For Each detailRow In orderRow.GetChildRows(orderDetailRelation)
            Console.WriteLine(vbTab & "   Product: " & _
              detailRow.GetParentRow(orderProductRelation) _
              ("ProductName").ToString())
            Console.WriteLine(vbTab & "  Quantity: " & _
              detailRow("Quantity").ToString())
        Next
    Next
Next

Zobacz także