Fabian Fabian - 2 years ago 151
C# Question

Add Many to Many object entity framework C#

I'm using EF and new to it. I have a many to many in my project

Suppose I have 3 tables

Class : ClassID-ClassName

Student : StudentID-FirstName

StudentClass : StudentID-ClassID

If I want to add Students to my class, is it necessary to pass all data for each student?

something like this:

Student Table:

StudentID Name
1 Andrew
2 James

Class Table:

ClassID Name
1 Math


using (var db = factory.CreateContext())
Class a = db.Classes.Where( x => x.ClassID == 1)

//Here if I create an Object with Student, Will it be stored in many to
//many table only passing StudentID ?
a.Students.Add( new Student { StudentID = 1 })
a.Students.Add( new Student { StudentID = 2 })

//or I should do this
//a.Students.Add( db.Students.where( x=> x.StudentID == 1))?

Answer Source

If you already have the students in the database, I highly recommend to do this

//Find the class
Class a = db.Classes.FirtsOrDefault( x => x.ClassID == 1);

//be sure this exist
if(a != null)
    //find the student
    Student s = db.Students.FirtsOrDefault( x=> x.StudentID == 1);

    //Allways check if the object exist on the database, 
    //the row could be removed from another part of your program.
    //Otherwise you will get an error on Add() because object is null
    if(s != null)

In case you have multiple students to add, you can search for those and then use AddRange

//find all the student you want (use the search you need)
Student students = db.Students.Where( x=> x.StudentID == 1 && x.StudentID == 2 && x.StudentID == 3);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download