In the context of relational database management system (RDBMS), foreign key is a field in one table that uniquely identifies a row of another table. In sql programming, foreign key is a column which points to the primary key of another table.
An entity can be related referenced with other entities through this foreign key, in entity framework. This can be done through an association between the tables. As we have studied in our Previous Post how to create databases and tables in it. In this article i will create a foreign key in the table.
Steps of creating foreign key in entity framework 5.
Here above i have mentioned the version of entity framework, because it is the stable version currently. Follow these steps and it will add a reference of student in address class.
- In our Previous post we have created a table Student. We will use this table here.
- In that same project add a new class Address and create some properties (fields in context of databases).
- In the Address class create a property type of Student having keyword virtual as written here:
public virtual Student Student { get; set; } - Now repeat the same procedure of creating an object of DataContext class in Form1's Constructor.
- And Finally we have successfully created a foreign key in Address table by running Form1.