Configure Many-to-Many relationship:
Configure Many-to-Many relationship:
Here, we will learn how to configure Many-to-Many relationship between the Student and Course entity classes. Student can join multiple courses and multiple students can join one course.
Visit Entity Relationship section to understand how EF manages one-to-one, one-to-many and many-to-many relationships between the entities.
Configure Many-to-Many relationship using DataAnnotation:
Student class should have a collection navigation property for Course, and Course should have a collection navigation property for student, which will create a Many-to-Many relationship between student and course as shown below:
public class Student
{
public Student() { }
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
public int StdandardId { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public Course()
{
this.Students = new HashSet<Student>();
}
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
The code shown above will create the following database, where Code-First will create a third joining table, CourseStudent, which will consist of the PK of both the tables, i.e. StudentId & CourseId:
Configure Many-to-Many relationship using Fluent API:
You can use the Fluent API to configure a Many-to-Many relationship between Student and Course, as shown below:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("StudentRefId");
cs.MapRightKey("CourseRefId");
cs.ToTable("StudentCourse");
});
}
As you can see in the above example, .HasMany<Course>(s => s.Courses).WithMany(c => c.Students)
says that Student and Course has many-to-many relationship with Students navigation property in Course class and Courses navigation property in Student class.
Map method takes Action type delegate, hence, we can pass lambda expression wherein we will specify FK property name of Student (we start with Student entity, so it will be left table) and FK of Course table. ToTable will create StudentCourse table.
This will create a new joining table StudentCourse with two Primary Keys which will also be Foreign Keys, as shown below:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix