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 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.
Click here to view big Image
Step 2: Now add a Department table.
Click here to view big Image
Step 3: Declare a variable and set the properties for the Department Table.
Click here to view big Image
Step 4: Add an Employee Table.
Click here to view big Image
Step 5: Declare variables of the Employee Table and set the properties. Also declare the Department Table as Virtual.
Click here to view 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#".
Click here to view big Image
Step 7: Add a Context Class as shown.
Click here to view big Image
Step 8: Now set the properties for the Employee and Department Classes in the Context Class.
Click here to view big Image
Step 9: Add an application configuration file.
Click here to view big Image
Step 10: Now declare the catalog or database name and the data source path of your SQL Server using a connection string.
Click here to view 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.
Click here to view big Image
Step 12: Press F5. It will show that the database was created successfully!!
Click here to view 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.
Click here to view big Image