Constraints
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"]); dt.Constraints.Add(uc); // add a foreign key constraint by reference (wxh - test) ForeignKeyConstraint fc = new ForeignKeyConstraint( dtParent.Columns["ParentColumn"], dtChild.Columns["ChildColumn"]); dt.Constraints.Add(fc);
Two overloads of the Add( )
method create and add
UniqueConstraint
objects in one statement. The ...
Get ADO.NET in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.