Creating Primary Key And Foreign Key Association in SQL Server Using Visual C# 2010 and Entity Framework

This article shows how to create a primary key and foreign key association in Employee and Department tables. I have used Dept_Id as the foreign key in the Employee table. In my previous article, I have shown how to add Entity Framework to Visual C#. Please check it once before going through this article. Here I am directly showing the creation of a primary key and foreign key association. You can download the Entity Framework.dll file from the internet and add it to Visual C#. The following is the procedure to create an association between foreign key and primary key.
Step 1: First create a console application and add it. Here I have named it FK_PK_Association_Application.
Step 2: Now add a Department table.
Step 3: Declare a variable and set the properties for the Department Table.
Step 4: Add an Employee Table.
Step 5: Declare variables of the Employee Table and set the properties. Also, declare the Department Table as Virtual.
Step 6: Add an Entity Framework to the FK_PK_Console Application. Add a reference to it as shown in the previous article named "Entity Framework Approach to Connect to Microsoft SQL Server and Visual C#".
Step 7: Add a Context Class as shown.
Step 8: Now set the properties for the Employee and Department Classes in the Context Class.
Step 9: Add an application configuration file.
Step 10: Now declare the catalog or database name and the data source path of your SQL Server using a connection string.
Step 11: Create an object for the Context Class, Employee Class, and Department Class and Initialize the database. A database initializer is a class that takes care of database creation and initialization in a Code First application. It is the job of the database initializer to create the database and the required tables based on the data model classes you create. Finally, add an Employee Object to the context.
Step 12: Press F5. It will show that the database was created successfully!!
Step 13: Login into SQL Server and check. Finally, the database named FK_PK_Association has been created.
As shown in the following figure.