Abdallah Sabri
Abdallah Sabri

Reputation: 441

Handling checkbox in Many-to-Many Entity Framework 6

I'm using MVC 5, EntityFramwork 6, Code first approach

I see a lot of example in using checkbox in entity framework, but I didn't see any case like what I need.

I will use this simple case:

I have two simple Course and Student, Every Course has many Students. Every Student has many Courses.

In EF models:

Course class is

public class Course
{
    public int ID { get; set; }
    public string Title { get; set; }
    public List<Student> Students { get; set; }
}

and Student class is

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
}

This generates a table in database called CourseStudents table which contains 1 composite Primary key and 2 foreign Keys as expected.

THE QUESTION IS:

I want to create a simple Create view contains Student name and list of Courses (displayed as checkboxes), the selected checkboxes is stored in CourseStudents table

How to do that?

Upvotes: 0

Views: 795

Answers (1)

Tawfiq abu Halawah
Tawfiq abu Halawah

Reputation: 1234

on submit 1. Create new student object. 2. add selected courses to student object couse list

myStudent.Courses.add(selectedCourse);
  1. after adding all courses add student to dbContext and save changes to dbContext

    context.students.add(myStudent)
    context.SaveChanges();

if the student already exist just select it and add courses to selected student list and save changes to dbContext

Upvotes: 2

Related Questions