DataTable.Constraints 属性


获取由该表维护的约束的集合。Gets the collection of constraints maintained by this table.

 property System::Data::ConstraintCollection ^ Constraints { System::Data::ConstraintCollection ^ get(); };
public System.Data.ConstraintCollection Constraints { get; }
public System.Data.ConstraintCollection Constraints { get; }
member this.Constraints : System.Data.ConstraintCollection
member this.Constraints : System.Data.ConstraintCollection
Public ReadOnly Property Constraints As ConstraintCollection



一个 ConstraintCollection,包含该表的 Constraint 对象的集合。A ConstraintCollection that contains the collection of Constraint objects for the table. 如果 Constraint 对象不存在,将返回空集合。An empty collection is returned if no Constraint objects exist.



下面的示例将添加 ForeignKeyConstraint 到约束的集合。The following example adds a ForeignKeyConstraint to the collection of constraints.

private void CreateConstraint(DataSet dataSet,
    string table1, string table2, string column1, string column2)
    ForeignKeyConstraint idKeyRestraint = new

    // 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.EnforceConstraints = true;
Private Sub CreateConstraint(dataSet As DataSet, _
    table1 As String, table2 As String, _
    column1 As String, column2 As String)

    Dim idKeyRestraint As ForeignKeyConstraint = _
        New ForeignKeyConstraint _
        (dataSet.Tables(table1).Columns(column1), _

    ' 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.EnforceConstraints = True
End Sub


ForeignKeyConstraint限制在删除或更新列中的值 (或列) 时执行的操作。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).

  • 子列 (或列) 中的值可以设置为 null 值。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.

UniqueConstraint当尝试将主键中的值设置为非唯一值时,将变为活动状态。A UniqueConstraint becomes active when attempting to set a value in a primary key to a non-unique value.