Incorrect DataRelation.ChildKeyConstraint property example (319413)



The information in this article applies to:

  • Microsoft ADO.NET (included with the .NET Framework 1.1)
  • Microsoft ADO.NET (included with the .NET Framework) 1.0
  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q319413

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
				

Modification Type:MinorLast Reviewed:9/15/2005
Keywords:kbvs2002sp1sweep kbbug kbdocerr kbpending KB319413 kbAudDeveloper