How to add a new entry to the EF many-to-many relationship?

I am working on my training project. I am new to entity infrastructure.

I have many two relationship tables. I use the code first. enter image description here

Here is the definition of the tables:

class EmployeeDBContext : DbContext { public EmployeeDBContext() : base("DefaultConnection") { } public DbSet<Course> Courses { get; set; } public DbSet<Student> Students { get; set; } } //================================================My entities================================================= public class Student { [Key] public int StudentID { get; set; } public string StudentName { get; set; } public virtual ICollection<Course> Courses { get; set; } } public class Course { [Key] public int CourseID { get; set; } public string CourseName { get; set; } public virtual ICollection<Student> Students { get; set; } } 

A course table filled with three topics: history, mathematics, physics.

I need to add a new student and associate the student with existing courses.

Any idea how I can implement it?

Thanks in advance.

+4
source share
2 answers

If you need to create a student and add a course (or more courses) to it, then the way to do it with EF will be the same as described with the words ...

 using (var ctx= new EmployeeDBContext()) { // Create a new student (and set some properties) Student student = new Student() { StudentName = "Scott Tiger" }; // Replace courseId with the course id that you need to add to the student student.Courses.Add(ctx.Courses.Find(courseId)); // Add other courses if you need to // Let write the student to the DB ctx.Students.Add(student); ctx.SaveChanges(); } 
+2
source

Try using the code below: Depends if you want to update the course name or add a list of students.

  public void UpdateCourse(string courseName, List<Student> students) { var dbInstance = new EmployeeDBContext(); Course model = (from item in dbInstance.Courses where item.CourseID = courseid select item); model.CourseName = courseName; foreach(var item in students) { var currentStudent = from stud in dbInstance.Students where stud.StudentId == item.StudentId; if( currentStudent != null) currentStudent.Name = item.Name; else dbInstance.Students.Add(new Student() {.StudentId = item.StudentId, .Name = item.Name}); }; dbInstance.SaveChanges(); } public void CreateCourse(string courseName, List<Student> students) { var model = new Course(); model.CourseName = courseName; model.Students = students; var dbInstance = new EmployeeDBContext(); dbInstance.Courses.Add(model); dbInstance.SaveChanges(); } 
+2
source

All Articles