Esplorazione di oggetti DataRelation

Una delle funzioni principali di un oggetto DataRelation è di consentire la navigazione da una DataTable all'altra all'interno di un DataSet. In questo modo è possibile recuperare tutti gli oggetti DataRow correlati all'interno di una DataTable nel caso in cui venga dato un singolo oggetto DataRow proveniente da una DataTable correlata. Dopo aver ad esempio stabilito una DataRelation tra una tabella di clienti e una tabella di ordini, è possibile recuperare tutte le righe di ordine relative a un particolare cliente usando GetChildRows.

Nell'esempio di codice seguente viene creata una DataRelation tra la tabella Customers e la tabella Orders di un DataSet e vengono restituiti tutti gli ordini per ogni cliente.

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

Nell'esempio successivo, basato su quello precedente, vengono correlate quattro tabelle e vengono esplorate tali relazioni. Come mostrato nell'esempio precedente, CustomerID consente di correlare la tabella Customers alla tabella Orders. Per ogni cliente della tabella Customers vengono determinate tutte le righe figlio della tabella Orders, in modo da restituire il numero di ordini associati a un determinato cliente e i relativi valori OrderID.

Nell'esempio espanso, inoltre, vengono restituiti i valori delle tabelle OrderDetails e Products. La tabella Orders è correlata alla tabella OrderDetails tramite OrderID, che consente di determinare i prodotti e le quantità ordinate per ogni ordine cliente. Poiché la tabella OrderDetails contiene solo il ProductID di un prodotto ordinato, la tabella OrderDetails è correlata alla tabella Products tramite ProductID, in modo da restituire il valore ProductName. In questo tipo di relazione, Products è la tabella padre mentre Order Details è la tabella figlio. Di conseguenza, quando si esegue una reiterazione della tabella OrderDetails, GetParentRow viene chiamato per consentire il recupero del valore ProductName correlato.

Notare che al momento della creazione dell'oggetto DataRelation per le tabelle Customers e Orders non viene specificato alcun valore per il flag createConstraints (il valore predefinito è true). Si presuppone che tutte le righe della tabella Orders dispongano di un valore CustomerID esistente nella tabella padre Customers. Se la tabella Orders contiene un valore CustomerID non presente nella tabella Customers, un vincolo ForeignKeyConstraint provocherà un'eccezione.

Se è possibile che nella colonna figlio siano presenti valori non contenuti nella colonna padre, impostare il flag createConstraints su false quando si aggiunge l'oggetto DataRelation. Nell'esempio seguente il flag createConstraints viene impostato su false per l'oggetto DataRelation tra la tabella Orders e la tabella OrderDetails. Ciò consente all'applicazione di restituire tutti i record della tabella OrderDetails e solo un subset di record della tabella Orders, senza che venga generata alcuna eccezione in fase di esecuzione. Nell'esempio espanso viene generato un output con il seguente formato.

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  

L'esempio di codice seguente è un esempio espanso, in cui vengono restituiti i valori delle tabelle OrderDetails e Products e solo un subset di record della tabella 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

Vedi anche