DataRelation Object Overview

Every DataSet contains a DataRelationCollection object, which contains DataRelation objects. Each DataRelation defines a relationship between two tables. There are two reasons why you might define DataRelation objects:

  • To provide better error checking (for example, spotting an orphaned child before you reconnect to update the data source). This functionality is provided through the ForeignKeyConstraint, which the DataRelation can create implicitly.

  • To provide better navigation.

A typical DataRelation requires three pieces of information: a descriptive name of your choosing (which doesn’t signify anything or relate to the data source), a reference to the parent DataColumn, and a reference to the child DataColumn. You can add this information with the DataRelation constructor:

DataRelation relation = new DataRelation("Name", ParentCol, ChildCol);

Once you’ve defined the DataRelation object, you need to add it to the DataSet:

ds.Relations.Add(relation);

For example, to create a relationship between product categories and products, use the following code:

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

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

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



ds.Relations.Add(relation);

If you attempt to create a DataRelation, and the parent record column isn’t unique, or there are child records that refer to nonexistent parents, an exception is thrown.

Tip

Currently, ...

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.