DataTable.Constraints Property

Definition

Gets the collection of constraints maintained by this table.

C#
public System.Data.ConstraintCollection Constraints { get; }
C#
[System.Data.DataSysDescription("DataTableConstraintsDescr")]
public System.Data.ConstraintCollection Constraints { get; }

Property Value

A ConstraintCollection that contains the collection of Constraint objects for the table. An empty collection is returned if no Constraint objects exist.

Attributes

Examples

The following example adds a ForeignKeyConstraint to the collection of constraints.

C#
private void CreateConstraint(DataSet dataSet,
    string table1, string table2, string column1, string column2)
{
    ForeignKeyConstraint idKeyRestraint = new
        ForeignKeyConstraint(dataSet.Tables[table1].Columns[column1],
        dataSet.Tables[table2].Columns[column2]);

    // Set null values when a value is deleted.
    idKeyRestraint.DeleteRule = Rule.SetNull;
    idKeyRestraint.UpdateRule = Rule.Cascade;

    // Set AcceptRejectRule to cascade changes.
    idKeyRestraint.AcceptRejectRule = AcceptRejectRule.Cascade;

    dataSet.Tables[table1].Constraints.Add(idKeyRestraint);
    dataSet.EnforceConstraints = true;
}

Remarks

A ForeignKeyConstraint restricts the action performed when a value in a column (or columns) is either deleted or updated. Such a constraint is intended to be used with primary key columns. In a parent/child relationship between two tables, deleting a value from the parent table can affect the child rows in one of the following ways.

  • The child rows can also be deleted (a cascading action).

  • The values in the child column (or columns) can be set to null values.

  • The values in the child column (or columns) can be set to default values.

  • An exception can be generated.

A UniqueConstraint becomes active when attempting to set a value in a primary key to a non-unique value.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

See also