Chapter 7: Working with Data

189

Figure 7-7 Configuring a foreign key relationship

In the primary key table drop-down, shown in Figure 7-7, select Customer, which

automatically selects the primary key, CustomerID. (Note: If you don’t see this behavior, check to see that you’ve set your primary key columns and saved those table changes as described earlier.) In the list, under Foreign Key Table in Figure 7-7, you’ll initially see OrderID, which is the primary key of the order table. Select OrderID and change it to CustomerID as the foreign key column. Click OK to exit and click Close to finalize creation of the foreign key relationship. When you click Save to save the new foreign key relationship, you’ll see a warning message similar to Figure 7-8, listing the tables participating in the change. Select Yes to make your changes to the SQL Server tables. You can uncheck the Warn About Tables Affected box if you don’t want to see this message anymore, but the message does serve as a safety net to make sure you don’t accidentally save unintended changes to SQL Server, which is an external product to VS 2010.

Once the foreign key is in place, you can add a few records to the Order table, much as you did with the Customer table, but remember that the CustomerID must match

an existing CustomerID in the Customer table because of the foreign key relationship. Forcing the child to refer to its parent is good because it maintains the integrity of the database, demonstrating the value of a foreign key.

Page 212
Image 212
Microsoft 9GD00001 manual 189, Configuring a foreign key relationship