score:1

Accepted answer

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
 }

Related Query

More Query from same tag