Fabian Fabian - 10 months ago 41
C# Question

Add many-to-many object in 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


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))?
}

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

a.Students.AddRange(students);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download