In a relational database, it's imperative that the integrity of the data be maintained. One way of maintaining integrity in ADO+ is by adding constraints to tables. A constraint is an automatic rule that determines the course of action when the value of a row is somehow altered. There are two kinds of constraints found in ADO+: the ForeignKeyConstraint, and the UniqueConstraint.
When a value in a row is deleted or updated, and the value is also used in one or more related tables, a ForeignKeyConstraint determines what happens in the second table that is linked to the same column through a DataRelation. Possible actions include:
To use the ForeignKeyConstraint, create the ForeignKeyConstraint, then set the DeleteRule and UpdateRule properties to one of the appropriate values, as shown in the example below:
[VB]
Dim fk As ForeignKeyConstraint = _ New ForeignKeyConstraint(ds.Tables("Customers").Columns("CustID"), _ ds.Tables("Orders").Columns("CustID")) fk.DeleteRule = Cascade fk.UpdateRule = SetDefault ' Add the constraint to the Customers table. ds.Tables(0).Constraints("Customers").Constraints.Add(fk)
[C#]
ForeignKeyConstraint fk = new ForeignKeyConstraint(ds.Tables ["Customers"].Columns["CustID"], ds.Tables["Orders"].Columns["CustID"]); fk.DeleteRule = Cascade; fk.UpdateRule = SetDefault; ds.Tables["Customers"].Constraints.Add(fk);
When it's imperative that all the values in a column must be unique, you can add a UniqueConstraint to the DataTable. The UniqueConstraint can be assigned either a single column, or an array of columns (of the same DataTable), and ensure that all values in the column are unique.
[VB]
Dim uc As UniqueConstraint = _ New UniqueConstraint(ds.Tables("Customers").Columns.("CustID")) ' Add the consstraint to the Customers table. ds.Tables("Customers").Constraints.Add(uc)
[C#]
Data.UniqueConstraint uc = new UniqueConstraint(ds.Tables("Customers").Columns.("CustID"); // Add the consstraint to the Customers table. ds.Tables["Customers"].Constraints.Add(uc);