Freigeben über


Adding a Relationship Between Tables 

In a DataSet with multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table.

The arguments required to create a DataRelation are a name for the DataRelation being created, and an array of one or more DataColumn references to the columns that serve as the parent and child columns in the relationship. After you have created a DataRelation, you can use it to navigate between tables and to retrieve values.

Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table. For more information about these default constraints, see Adding Constraints to a Table.

The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.

customerOrders.Relations.Add("CustOrders", _
  customerOrders.Tables("Customers").Columns("CustID"), _
  customerOrders.Tables("Orders").Columns("CustID"))
customerOrders.Relations.Add("CustOrders",
  customerOrders.Tables["Customers"].Columns["CustID"],
  customerOrders.Tables["Orders"].Columns["CustID"]);

A DataRelation also has a Nested property which, when set to true, causes the rows from the child table to be nested within the associated row from the parent table when written as XML elements using WriteXml . For more information, see Using XML in a DataSet.

See Also

Other Resources

Using DataSets in ADO.NET