Partager via


Adding a Relationship between Tables

In a DataSet that contains 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.

custDS.Relations.Add("CustOrders", _
                     custDS.Tables("Customers").Columns("CustID"), _
                     custDS.Tables("Orders").Columns("CustID"))
[C#]
custDS.Relations.Add("CustOrders",
                     custDS.Tables["Customers"].Columns["CustID"],
                     custDS.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 XML and the DataSet.

See Also

Creating and Using DataSets | DataColumn Class | DataRelation Class | DataRelationCollection Class | DataSet Class | DataTable Class