To complete this task, I am going to create Employee and Department Model Class and let’s see how to make relationship. Following are the two model class.

  1. public class Department
  2. {
  3. [Key]
  4. public int DepartmentId { get; set; }
  5. [Required]
  6. public string DepartmentName { get; set; }
  7. }
  8. public class Employee
  9. {
  10. [Key]
  11. public int EmployeeId { get; set; }
  12. [Required]
  13. public string EmployeeName { get; set; }
  14. }
Department Model has primary key as DepartmentId and Employee Model has primary key as EmployeeId. I am going to create a foreign key of DepartmentId in Employee Model.
  1. public class Department
  2. {
  3. [Key]
  4. public int DepartmentId { get; set; }
  5. [Required]
  6. public string DepartmentName { get; set; }
  7. }
  8. public class Employee
  9. {
  10. [Key]
  11. public int EmployeeId { get; set; }
  12. [Required]
  13. public string EmployeeName { get; set; }
  14. // Foreign key
  15. [Display(Name = "Department")]
  16. public virtual int DepartmentId { get; set; }
  17. [ForeignKey("DepartmentId")]
  18. public virtual Department Departments { get; set; }
  19. }
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter.
  1. [ForeignKey("DepartmentId")]
  2. public virtual Department Departments { get; set; }
You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the Foreign key table.
  1. [Display(Name = "Department")]
  2. public virtual int DepartmentId { get; set; }
Thanks for reading this article, hope you enjoyed it.