SUMMARY
In the MSDN Library Topic
DataRelation.ChildKeyConstraint
Property and in the Visual Studio Help topic
"DataRelation.ChildKeyConstraint Property," the sample code is incorrect. The
Help Topics describe how to obtain the
ForeignKeyConstraint for the relation.
The sample code is incorrect because
it creates a
DataRelation object and then tries to get the
ForeignKeyConstraint object from its
ChildKeyConstraint property immediately after that. The following code is an example
of the incorrect sample code:
Private Sub SetChildKeyConstraint(ds As DataSet)
Dim dr As DataRelation
Dim cCol As DataColumn
Dim pCol As DataColumn
' Set child and parent columns.
pCol = ds.Tables("Suppliers").Columns("SupplierID")
cCol = ds.Tables("Products").Columns("SupplierID")
dr = New DataRelation("SuppliersConstraint", pCol, cCol)
Dim fk As ForeignKeyConstraint = dr.ChildKeyConstraint
fk.DeleteRule = Rule.SetNull
fk.UpdateRule = Rule.Cascade
fk.AcceptRejectRule = AcceptRejectRule.Cascade
End Sub
If you run the code, a System.NullReferenceException is thrown and you
receive the following error message:
Object reference
not set to an instance of an object.
CAUSE
The
ChildKeyConstraint property of the
DataRelation is not instantiated unless you add the
DataRelation object to the
DataSet first.
RESOLUTION
Before you access the Constraints of a
DataRelation object, add the
DataRelation object to the relations collection of the
DataSet. The correct code sample is as follows:
Private Sub SetChildKeyConstraint(ds As DataSet)
Dim dr As DataRelation
Dim cCol As DataColumn
Dim pCol As DataColumn
' Set child and parent columns.
pCol = ds.Tables("Suppliers").Columns("SupplierID")
cCol = ds.Tables("Products").Columns("SupplierID")
dr = New DataRelation("SuppliersConstraint", pCol, cCol)
ds.Relations.Add(dr)
Dim fk As ForeignKeyConstraint = dr.ChildKeyConstraint
fk.DeleteRule = Rule.SetNull
fk.UpdateRule = Rule.Cascade
fk.AcceptRejectRule = AcceptRejectRule.Cascade
End Sub