This article will demonstrate how to implement primary key and foreign key relationship in Code First approach in Entity Framework.
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.
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Required]
public string DepartmentName { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Required]
public string EmployeeName { get; set; }
}
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.
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Required]
public string DepartmentName { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Required]
public string EmployeeName { get; set; }
// Foreign key
[Display(Name = "Department")]
public virtual int DepartmentId { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Departments { get; set; }
}
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter.
[ForeignKey("DepartmentId")]
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.
[Display(Name = "Department")]
public virtual int DepartmentId { get; set; }
Thanks for reading this article, hope you enjoyed it.
Posted Comments :
fdfdfdfd Posted : 2 Years Ago
dd
Diego Posted : 2 Years Ago
Lamentablemente no me funcionó en asp core 6 con entity framework
Gyan Posted : 3 Years Ago
I am trying by using Migration giving error.... can u help me...