Updating data in a many-to-many relationship in the entity framework in the first code database

I am working on an application and am struggling to figure out how to update data in tables where we have an intermediate join table (ie a table to break many-to-many relationships). for example from the following diagram. if I say that I want to add an entry for a new student with a list of three courses, i.e. math, English and computing. how i do it when i have

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

      

enter image description here

other questions; another scenario, if i have courses already and of course i don't want duplicate math, english and course title, how to add a new copy 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, I need to use the virtual keyword in the above code.

+3


source to share


1 answer


First, if you don't have an extra field in StudentCourse

(such a registration semester), you don't need to have a class StudentCourse

.

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 can give you additional explanations:



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 a duplicate, you can simply do this:

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

      

+1


source







All Articles