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.


1. One-to-One Relationship

A one-to-one relationship exists when a record in one table is linked to exactly one record in another table.

Example: Student and StudentAddress

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; }  
}  

2. One-to-Many Relationship

A one-to-many relationship means a single record in one table is related to multiple records in another table.

Example: Teacher and Students

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; }  
}  

3. Many-to-Many Relationship

A many-to-many relationship requires a junction table that connects two entities.

Example: Students and Courses

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.

⚠️ **GitHub.com Fallback** ⚠️