07_Relationships Between Tables in Code First Approach (Using Data Annotations) - Maniconserve/EF-Core GitHub Wiki
In the Code First Approach, relationships between tables can be established using Data Annotations. Below are different types of relationships with their respective annotations.
A one-to-one relationship exists when a record in one table is linked to exactly one record in another table.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public StudentAddress Address { get; set; }
}
public class StudentAddress
{
[Key, ForeignKey("Student")]
public int Id { get; set; }
public string City { get; set; }
public Student Student { get; set; }
}
A one-to-many relationship means a single record in one table is related to multiple records in another table.
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Teacher")]
public List<Student> Students { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Teacher")]
public int TeacherId { get; set; }
public Teacher Teacher { get; set; }
}
A many-to-many relationship requires a junction table that connects two entities.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Students")]
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
[InverseProperty("Courses")]
public List<Student> Students { get; set; }
}
These are the different types of relationships you can define in Code First Approach using Data Annotations.