0

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))?
 }
1
  • Just creating the Class and then adding two new Student entities to its list of Students is sufficient - when you store this, EF will work out all the details of generating new Id's (if you have IDENTITY columns) and settings those in the necessary places, including the "many-to-many link" table Commented Aug 17, 2017 at 5:08

1 Answer 1

1

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 it exists
if(a != null)
{
    // find the student
    Student s = db.Students.FirtsOrDefault(x => x.StudentID == 1);

    // Always 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)
    {
        a.Students.Add(s);
    }
}

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

// 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);

if(students.Count > 0){
    a.Students.AddRange(students);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Check if(object != null) is very important, also if you don't check this you'll get an error even when reading a property of the object like: object.name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.