System.Data Namespace ConstraintCollection Class
Constructs a new ForeignKeyConstraint, with the specified parent and child columns, and adds the constraint to the collection.
[ VB ]
Overridable Overloads Public Function Add ( _
ByVal name As String, _
ByVal primaryKeyColumn As DataColumn, _
ByVal foreignKeyColumn As DataColumn _
) As Constraint
[ C# ]
public virtual Constraint Add (
String name,
DataColumn primaryKeyColumn,
DataColumn foreignKeyColumn
);
[ C++ ]
public: virtual Constraint* Add (
String* name,
DataColumn* primaryKeyColumn,
DataColumn* foreignKeyColumn
);
[ JScript ]
public function Add (
name : String,
primaryKeyColumn : DataColumn,
foreignKeyColumn : DataColumn
) : Constraint
- name
- The name of the UniqueConstraint.
- primaryKeyColumn
- The primary key DataColumn.
- foreignKeyColumn
- The foreign key DataColumn.
A ForeignKeyConstraint and UniqueConstraint are both created and added automatically when a DataRelation is added to a DataSet object's DataRelationCollection. The ForeignKeyConstraint ( which gets the same name as the DataRelation ) is added to the child table's ConstraintCollection, and the UniqueConstraint is added to the parent table's ConstraintCollection.
In this case, if you add a second ForeignKeyConstraint using this Add method, an exception will occur because an identical ForeignKeyConstraint is already in the collection. To avoid this, use the ForeignKeyConstraint constructor to create the ForeignKeyConstraint and test it against existing collection members with the Equals method.
The following example adds a new ForeignKeyConstraint to the ConstraintCollection of a DataTable.
private void AddForeignConstraint ( DataSet myDataSet ) {
try {
DataColumn parentCol = myDataSet.Tables [ "Suppliers" ].Columns [ "SupplierID" ];
DataColumn childCol = myDataSet.Tables [ "Products" ].Columns [ "SupplierID" ];
myDataSet.Tables [ "Products" ].Constraints.Add ( "ProductsSuppliersCstr", parentCol, childCol );
}
catch ( Exception myException ) {
// in case the constraint already exists, catch the collision here.
Response.Write ( myException.Message );
}
}
Private Sub AddForeignConstraint ( myDataSet As DataSet )
Try
Dim parentCol As DataColumn = myDataSet.Tables ( "Suppliers" ).Columns ( "SupplierID" )
Dim childCol As DataColumn = myDataSet.Tables ( "Products" ).Columns ( "SupplierID" )
myDataSet.Tables ( "Products" ).Constraints.Add ( "ProductsSuppliersCstr", parentCol, childCol )
Catch myException As Exception
' in case the constraint already exists, catch the collision here.
Response.Write ( myException.Message )
End Try
End Sub |
|
C# |
VB |
ConstraintCollection Members ConstraintCollection.Add Overload List