Add a Primary and Foreign Key Relationship in CodeFirst

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 { getset; }  
  5.   
  6.    [Required]  
  7.    public string DepartmentName { getset; }  
  8. }  
  9.   
  10. public class Employee  
  11. {  
  12.    [Key]  
  13.    public int EmployeeId { getset; }  
  14.   
  15.    [Required]  
  16.    public string EmployeeName { getset; }  
  17.   
  18. }  
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 { getset; }  
  5.   
  6.    [Required]  
  7.    public string DepartmentName { getset; }  
  8. }  
  9.   
  10. public class Employee  
  11. {  
  12.    [Key]  
  13.    public int EmployeeId { getset; }  
  14.   
  15.    [Required]  
  16.    public string EmployeeName { getset; }  
  17.   
  18.    // Foreign key   
  19.    [Display(Name = "Department")]  
  20.    public virtual int DepartmentId { getset; }  
  21.   
  22.    [ForeignKey("DepartmentId")]  
  23.    public virtual Department Departments { getset; }  
  24. }  
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 { getset; }  
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 { getset; }  
Thanks for reading this article, hope you enjoyed it.

Ebook Download
View all
Learn
View all