K.Z
K.Z

Reputation: 5075

updating data in many-to-many relationship in entity framework in code first existing database

I am working on app and struggling to really understand how to update data in tables where we have intermediate join table (i.e. table to break many-to-many relationship). for example, from following diagram. if I say I want to add record for new student with list of three courses i.e. math, English and computing. how I do that where I have

public virtual ICollection<StudentCourse> StudentCourses { get; set; } 

enter image description here

another questions; another scenario if I have courses already and of-course I don't want duplication of math, English and computing course title, how I add new instance of student record there??

Student

 public partial class Student
 {
    public Student()
    {
        this.StudentCourses = new HashSet<StudentCourse>();
    }

    public int StudentID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}

Course

 public partial class Course
{
    public Course()
    {
        this.StudentCourses = new HashSet<StudentCourse>();
    }

    public int CourseID { get; set; }
    public string Title { get; set; }

    public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}

Intermediate model

public partial class StudentCourse
{
    public int StudentCourseID { get; set; }
    public int StudentID { get; set; }
    public int CourseID { get; set; }

    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}

My third question is, do I have to use Virtual key word in above code.

Upvotes: 3

Views: 1049

Answers (1)

renakre
renakre

Reputation: 8291

First, if you do not have an additional field in StudentCourse (such semester of the registration), then you do not need to have StudentCourse class.

If you want to keep this mode, you can do this:

StudentCourse registration = new  StudentCourse();
registration.StudentID = 4;
registration.CourseID = 6;
context.StudentCourses.Add(registration);
context.SaveChanges();

These resources may give you further explanation:

https://practiceaspnet.wordpress.com/2015/10/22/code-first-many-to-many-mm-relationships-using-conventions-and-data-annotations/

https://practiceaspnet.wordpress.com/2015/10/30/managing-data-in-many-to-many-relationships-with-entity-framework-code-first/

If you want to check if there is no duplicate, you can simple do these:

 if(context.Courses.Where(c => c.Title == 'Math').FirstOrDefault() == null)
 {
     //add the course
 }else {
     //already existing
 }

Upvotes: 1

Related Questions