SQL Server Primary & Foreign Key Association: Visual C# 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 the foreign key and the primary key.

Step 1. First, create a console application and add it. Here I have named it FK_PK_Association_Application.

Association Application

Click here to view the big Image

Step 2. Now add a Department table.

Department table

Click here to view the big Image

Step 3. Declare a variable and set the properties for the Department Table.

Declare a variable

Click here to view the big Image

Step 4. Add an Employee Table.

 Employee Table

Click here to view the big Image

Step 5. Declare variables of the Employee Table and set the properties. Also, declare the Department Table as Virtual.

Department Table as Virtual

Click here to view the big Image

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#".

Entity Framework

Click here to view the big Image

Step 7. Add a Context Class as shown.

Context Class

Click here to view the big Image

Step 8. Now set the properties for the Employee and Department Classes in the Context Class.

Employee and Department Classes

Click here to view the big Image

Step 9. Add an application configuration file.

Configuration file

Click here to view the big Image

Step 10. Now declare the catalog or database name and the data source path of your SQL Server using a connection string.

SQL Server

Click here to view the big Image

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.

 Employee Object

Click here to view the big Image

Step 12. Press F5. It will show that the database was created successfully!!

Press F5

Click here to view the big Image

Step 13. Login into SQL Server and check. Finally, the database named FK_PK_Association has been created. As shown in the following figure.

Login into SQL Server

Click here to view the big Image


Similar Articles