isting departments in the Department table. However, as with primary keys, just
having the correct fields in place doesn’t mean that our data is guaranteed to be
correct.
For example, try setting the DepartmentID field for one of the employees to 123.
SQL Server won’t mind making the change for you, so if you tried this in practice,
you’d end up storing invalid data. However, after we set the foreign keys correctly,
SQL Server will be able to ensure the integrity of our data—specifically, it will
forbid us to assign employees to nonexistent departments, or to delete departments
with which employees are associated.
The easiest way to create foreign keys using Visual Web Developer or SQL
Server Management Studio is through database diagrams, so let’s learn about
them.
Using Database Diagrams
To keep the data consistent, the Dorknozzle database really should contain quite
a few foreign keys. The good news is that you have access to a great feature called
database diagrams, which makes it a cinch to create foreign keys. You can define
the table relationships visually using the database diagrams tool in Visual Web
Developer or SQL Server Management Studio, and have the foreign keys generated
for you.
Database diagrams weren’t created specifically for the purpose of adding foreign
keys. The primary use of diagrams is to offer a visual representation of the tables
in your database and the relationships that exist between them, to help you to
design the structure of your database. However, the diagrams editor included in
Visual Web Developer and SQL Server Management Studio is very powerful, so
you can use the diagrams to create new tables, modify the structure of existing
tables, or add foreign keys.
Let’s start by creating a diagram for the Dorknozzle database. To create a database
diagram in Visual Web Developer, right-click the Database Diagrams node, and
select Add New Diagram, as shown in Figure 7.15.
The process is similar in SQL Server Management Studio, which, as Figure 7.16
illustrates, has a similar menu.
The first time you try to create a diagram, you’ll be asked to confirm the creation
of the database structures that support diagrams. Select Yes from the dialog,
which should look like the one shown in Figure 7.17.
280
Chapter 7: Database Design and Development