Reputation: 5075
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; }
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??
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; }
}
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; }
}
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
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:
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