Esplorazione di una relazione tra tabelle

Una delle funzioni principali di un oggetto DataRelation consiste nel consentire lo spostamento da un oggetto DataTable all'altro in un DataSet. Risulta quindi possibile recuperare tutti gli oggetti DataRow correlati in 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 utilizzando DataRow.GetChildRows.

L'esempio di codice seguente consente di creare una DataRelation tra la tabella Customers e la tabella Orders di un DataSet e di restituire tutti gli ordini per ogni cliente.

Dim custOrderRel As DataRelation = custDS.Relations.Add("CustOrders", _
                     custDS.Tables("Customers").Columns("CustomerID"), _
                     custDS.Tables("Orders").Columns("CustomerID")) 

Dim custRow As DataRow
Dim orderRow As DataRow

For Each custRow in custDS.Tables("Customers").Rows
  Console.WriteLine(custRow("CustomerID"))
  For Each orderRow in custRow.GetChildRows(custOrderRel)
    Console.WriteLine(orderRow("OrderID"))
  Next
Next
[C#]
DataRelation custOrderRel = custDS.Relations.Add("CustOrders",
                     custDS.Tables["Customers"].Columns["CustomerID"],
                     custDS.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow custRow in custDS.Tables["Customers"].Rows)
{
  Console.WriteLine(custRow["CustomerID"]);
  foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
    Console.WriteLine(orderRow["OrderID"]);
}

L'esempio successivo si basa sull'esempio precedente e consente di correlare quattro tabelle e di esplorare 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 figlie della tabella Orders, in modo da restituire il numero di ordini associati a un determinato cliente e i relativi valori OrderID.

L'esempio ampliato consente inoltre di restituire 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é nella tabella OrderDetails è contenuto solo il ProductID di un prodotto ordinato, la tabella OrderDetails è correlata a Products tramite ProductID, in modo da restituire ProductName. In questo tipo di relazione la tabella Products rappresenta il padre e la tabella Order Details il figlio. Quando si esegue una reiterazione della tabella OrderDetails quindi, GetParentRow viene chiamato per consentire il recupero del valore ProductName correlato.

Si noti 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 nella tabella Orders è presente un valore CustomerID non presente nella tabella Customers, un vincolo ForeignKeyConstraint provocherà un'eccezione.

Se è possibile che nella colonna figlia 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. L'applicazione risulta quindi in grado di restituire tutti i record della tabella OrderDetails e solo un sottoinsieme di record della tabella Orders, senza che venga generata alcuna eccezione di runtime. L'esempio ampliato consente di generare 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 ampliato, che consente di restituire i valori delle tabelle OrderDetails e Products e di restituire solo un sottoinsieme di record della tabella Orders.

Dim custOrderRel As DataRelation = custDS.Relations.Add("CustOrders", _
                     custDS.Tables("Customers").Columns("CustomerID"), _
                     custDS.Tables("Orders").Columns("CustomerID"))

Dim orderDetailRel As DataRelation = custDS.Relations.Add("OrderDetail", _
                     custDS.Tables("Orders").Columns("OrderID"), _
                     custDS.Tables("OrderDetails").Columns("OrderID"), false)

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

Dim custRow, orderRow, detailRow As DataRow

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

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

    For Each detailRow In orderRow.GetChildRows(orderDetailRel)
        Console.WriteLine(vbTab & "   Product: " & detailRow.GetParentRow(orderProductRel)("ProductName").ToString())
        Console.WriteLine(vbTab & "  Quantity: " & detailRow("Quantity").ToString())
    Next
  Next
Next
[C#]
DataRelation custOrderRel = custDS.Relations.Add("CustOrders",
                     custDS.Tables["Customers"].Columns["CustomerID"],
                     custDS.Tables["Orders"].Columns["CustomerID"]);

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

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

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

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

    foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRel))
    {
        Console.WriteLine("\t   Product: " + detailRow.GetParentRow(orderProductRel)["ProductName"]);
        Console.WriteLine("\t  Quantity: " + detailRow["Quantity"]);
    }
  }
}

Vedere anche

Creazione e utilizzo di DataSet | Classe DataRelation | Classe DataRow | Classe DataSet