Modeling Relationships
Unlock the power of EF Core by understanding and implementing various entity relationships: One-to-One, One-to-Many, and Many-to-Many.
Description
Each record in table A can be associated with at most one record in table B, and vice-versa.
Implementation
Typically achieved by having a foreign key in one table that references the primary key of the other, and a unique constraint on that foreign key.
Example
- User and UserProfile
- Order and OrderDetails (if details are distinct and singular)
Code Snippet:
public class User {
public int Id { get; set; }
public UserProfile Profile { get; set; }
}
public class UserProfile {
public int Id { get; set; }
public int UserId { get; set; } // Foreign Key
public User User { get; set; } // Navigation Property
}
Description
One record in table A can be associated with many records in table B, but each record in table B can only be associated with one record in table A.
Implementation
The "many" side of the relationship holds the foreign key to the "one" side.
Example
- Blog and Posts (A blog has many posts)
- Customer and Orders (A customer can have many orders)
Code Snippet:
public class Blog {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Post> Posts { get; set; } // Navigation Property
}
public class Post {
public int Id { get; set; }
public string Title { get; set; }
public int BlogId { get; set; } // Foreign Key
public Blog Blog { get; set; } // Navigation Property
}
Description
Records in table A can be associated with many records in table B, and vice-versa.
Implementation
Requires a third "junction" or "linking" table that contains foreign keys referencing the primary keys of both tables involved in the relationship.
Example
- Student and Course (A student enrolls in many courses, a course has many students)
- Post and Tag (A post can have many tags, a tag can be applied to many posts)
Code Snippet:
public class Student {
public int Id { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class Course {
public int Id { get; set; }
public string Title { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse {
public int StudentId { get; set; } // FK to Student
public Student Student { get; set; }
public int CourseId { get; set; } // FK to Course
public Course Course { get; set; }
}