]> Foreign Keys SMO 🌐:aligrant.com

Foreign Keys SMO

Alastair Grant | Wednesday 23 May 2007

Adding foreign keys with SQL SMO can be a little confusing. There is an example, but it's not very clear to me.

Here is a little sample, which is hopefully clearer. It assumes you've got a table that you wish to have the constraint put on already selected.

ForeignKey fk = new ForeignKey(myTable, "fk__constraint_name_here");
fk.Columns.Add(new ForeignKeyColumn(fk, "column_to_constrain", "column_on_other_table"));
fk.ReferenceTable = "the_other_table";
myTable.ForeignKeys.Add(fk);

Hope that makes a little more sense.

Breaking from the voyeuristic norms of the Internet, any comments can be made in private by contacting me.