As mentioned earlier, schema for a table is defined by the columns in the table and the constraints on those columns. There are two types of constraints that can be placed on a table. Unique constraints define a column or group of columns for which the value in the column or columns must be unique in each data row. Foreign key constraints define and restrict the action performed when a value in a column or columns is updated or deleted. Constraints belonging to the DataTable are stored as either UniqueConstraint or ForeignKeyConstraint objects in a ConstraintCollection object and are accessed through the Constraints property of the DataTable. This section examines some methods and properties of the ConstraintCollection .

To add a constraint to a table, the Add( ) method takes an argument specifying a reference to an existing constraint or takes specific arguments if a unique or foreign-key constraint is added. The following example demonstrates adding both a unique and foreign-key constraint by specifying a reference to an existing constraint:

// add a unique constraint by reference

UniqueConstraint uc = 

  new UniqueConstraint(dt.Columns["MyColumn"]);


// add a foreign key constraint by reference (wxh - test)

ForeignKeyConstraint fc = new ForeignKeyConstraint(




Two overloads of the Add( ) method create and add UniqueConstraint objects in one statement. The ...

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.