The ForeignKeyConstraint represents a restriction on a set of related columns. Usually, you don’t create a ForeignKeyConstraint directly. Instead, you define and add a DataRelation to the DataSet.Relations collection. A corresponding ForeignKeyConstraint is added automatically to the DataTable.Constraints collection of the child table. When you have a ForeignKeyConstraint on a DataTable, certain actions are not allowed (such as creating a parent that references a nonexistent parent row). You can disable checking for constraint violations by setting DataSet.EnforceConstraints to false.

The ForeignKeyConstraint allows you to configure what happens when the parent column is updated (UpdateRule), or when the parent row is deleted (DeleteRule) or has AcceptChanges( ) called on it (AcceptRejectRule). Out of these three options, the DeleteRule is the most commonly used. If you set the DeleteRule to Rule.Cascade, all child rows are deleted when the parent row is deleted. If you use Rule.SetNull, however, the foreign key field in the child record is set to a null value. If you use Rule.SetDefault, the foreign key field is set to a default value when the parent record is deleted. Finally, if you use Rule.None (the default), no action is taken. This results in an error when you attempt to remove a parent with child rows, when you have the DataSet.EnforceConstraints property set to true.

public class ForeignKeyConstraint : Constraint {

// Public Constructors

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.