Here, in fact, it all depends on the database creation hike using the Entity Framework :
A) If you use the DatabaseFirst approach, then for interaction you will need to create a third table manually for normal operation.
B) It is assumed that you are using CodeFirst and therefore your third table will be automatically generated by the Entity Framework
Now let's talk about how to interact with it.
1) Addition and output:
using(StudentContext db = new StudentContext()) { //Создание и добавление моделей Student student_one = new Student{StudentName = "Gregory"}; Student student_two = new Student{StudentName = "Trevor"}; db.Students.AddRange(new List<Student> { student_one, student_two});//добавляем в бд db.SaveChanges(); //Теперь курс Course c1 = new Course {CourseName ="test_course1"}; c1.Students.add(student_one); c1.Students.add(student_two); db.SaveChanges(); //Вывод foreach(Course c in db.Courses.Include(s=>s.Students)) { Console.WriteLine("Курс: {0}", s.CourseName); foreach(Student students in s.Students) { Console.WriteLine("{0}", students.StudentName); } Console.WriteLine(); } }
When adding one model to the list to another, it is important to remember that this list should already have been created, otherwise an exception will be thrown. In this case, we create a list in the constructor of both models. It is also possible to create a list directly in the program.
Editing table :
// удаляем связи с одним объектом Student student_edit = db.Students.First(st=>st.Name=="Trevor"); Course course_edit = student_edit.Courses.First(p=>p.Name=="test_course1"); course_edit.Players.Remove(student_edit);
It is important to understand that deleting a student simply from the team, we do not delete it completely from the database, as it can exist by itself, but if we delete the student, then the Course table will no longer be:
Student student_delete = db.Students.First(p=>p.Name=="Trevor"); db.Students.Remove(student_delete);
To update and edit information, we also need to break the link to start:
// удаляем связи с одним объектом Student student_edit = db.Students.First(st=>st.StudentName=="Trevor"); Course course_edit = student_edit.Courses.First(p=>p.Name=="test_course1"); course_edit.Players.Remove(student_edit); // создаем нового студента заместо старого Student student_three = new Student {StudentName = "Carl"}; // добавляем нового студента в бд course_edit.Students.Add(student_three); db.SaveChanges();
EntityFramework can read about data manipulations in EntityFramework in EntityFramework here and here.