DataRelation objects are contained in a DataRelationCollection. Every DataSet exposes a DataRelationCollection through its Relations property. In addition, you can access the DataRelation objects that pertain to a specific table through the DataTable.ChildRelations and DataTable.ParentRelations properties.

The DataRelation links two matching DataColumn objects from different tables. Thus, the data type of both columns must be identical. When a DataRelation object is created, the relationship is verified. Once you add the DataRelation to the DataSet.Relations collection, a ForeignKeyConstraint is generated for the child table, preventing changes that would violate relational integrity.

The following code creates and adds a DataRelation:

DataColumn parentCol = ds.Tables["Categories"].Columns["CategoryID"];

DataColumn childCol = ds.Tables["Products"].Columns["CategoryID"];

DataRelation dr = new DataRelation("Cat_Prod", parentCol, childCol);


Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.