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
My code:
using (var db = factory.CreateContext())
{
Class a = db.Classes.Where( x => x.ClassID == 1)
// Here if I create a `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 do I need do this?
// a.Students.Add( db.Students.where( x=> x.StudentID == 1))?
}
Classand then adding two newStudententities to its list ofStudentsis sufficient - when you store this, EF will work out all the details of generating new Id's (if you haveIDENTITYcolumns) and settings those in the necessary places, including the "many-to-many link" table