Creating, Altering, and Removing Foreign Keys

In SQL Server Management Objects (SMO), foreign keys are represented by the ForeignKey object.

To create a foreign key in SMO, you must specify the table on which the foreign key is defined in the constructor of the ForeignKey object. From the table, you must select at least one column to be the foreign key. To do this, create a ForeignKeyColumn object variable and specify the name of the column that is the foreign key. Then, specify the referenced table and referenced column. Use the Add method to add the column to the Columns object property.

The columns that represent the foreign key are listed in the Columns object property of the ForeignKey object. The primary key that is referenced by the foreign key is represented by the ReferencedKey property that is in the table specified in the ReferencedTable property.

Community Additions