I want to create a Many to Many relationship with Student table and IdentityUser table that EF provides. I created a Teacher Entity and Injected "IdentityUser". Below are the entities now -
1. Student
2. Teacher : IdentityUser
3. StudentTeacher
Any guides on how to do it?

Amit MohantyRank #112 · 20K reputationPosted Mar 29, 2023, 12:03 AM EDT
To create a many-to-many relationship between the Student and Teacher entities, you can use the StudentTeacher entity as a linking table. This table will have foreign keys to both the Student and Teacher entities.
For example:
public class Student { public int Id { get; set; } public string Name { get; set; } public ICollection StudentTeachers { get; set; } } public class Teacher : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public ICollection StudentTeachers { get; set; } } public class StudentTeacher { public int StudentId { get; set; } public Student Student { get; set; } public string TeacherId { get; set; } public Teacher Teacher { get; set; } }To configure the many-to-many relationship in EF, you can use the HasMany and WithMany methods in the OnModelCreating method of your DbContext.
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasKey(st => new { st.StudentId, st.TeacherId }); modelBuilder.Entity() .HasOne(st => st.Student) .WithMany(s => s.StudentTeachers) .HasForeignKey(st => st.StudentId); modelBuilder.Entity() .HasOne(st => st.Teacher) .WithMany(t => t.StudentTeachers) .HasForeignKey(st => st.TeacherId); }Jignesh KumarRank #91 · 22.9K reputationPosted Mar 28, 2023, 11:57 PM EDT
hello Bell,
Please refer this one which will help you out,
https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx