
DataRelation Objects and Constraints
A DataRelation object is also used to create and enforce the following constraints:
A unique constraint, which guarantees that a column in the table contains no duplicates.
A foreign-key constraint, which can be used to maintain referential integrity between a parent and child table in a dataset.
Constraints that you specify in a DataRelation object are implemented by automatically creating appropriate objects or setting properties. If you create a foreign-key constraint using the DataRelation object, instances of the ForeignKeyConstraint class are added to the DataRelation's ChildKeyConstraint property.
A unique constraint is implemented either by simply setting the Unique property of a data column to true or by adding an instance of the UniqueConstraint class to the DataRelation object's ParentKeyConstraint. For information on suspending constraints in a dataset, see How to: Turn Off Constraints While Filling a Dataset.
Referential Integrity Rules
As part of the foreign-key constraint, you can specify referential integrity rules that are applied at three points:
When a parent record is updated
When a parent record is deleted
When a change is accepted or rejected
The rules you can make are specified in the Rule enumeration and are listed in the following table.
Foreign-key constraint rule
|
Action
|
|---|
Cascade
|
The change (update or delete) made to the parent record is made in related records in the child table as well.
|
SetNull
|
Child records are not deleted, but the foreign key in the child records is set to DBNull. With this setting, child records can be left as "orphans" — that is, they have no relationship to parent records.
Note:
Using this rule can result in invalid data in the child table.
|
SetDefault
|
The foreign key in the related child records is set to its default value (as established by the column's DefaultValue property).
|
None
|
No change is made to related child records. With this setting, child records can end up containing references to invalid parent records.
|
For more information about updates in dataset tables, see Saving Data Overview.
Constraint-only Relations
When creating a DataRelation object, you have the option of specifying that the relation be used only to enforce constraints — that is, it will not also be used to access related records. This option allows you to generate a dataset that is slightly more efficient and that contains fewer methods than one with the related-records capability. However, you will not be able to access related records. For example, a constraint-only relation prevents you from deleting a parent record that still has children, and you cannot access the child records through the parent.