Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert/Update Many to Many Entity Framework . How do I do it?

I'm using EF4 and new to it. I have a many to many in my project and cannot seem to work out how to insert or update. I have build a small project just to see how it should be coded.

Suppose I have 3 tables

  1. Class : ClassID-ClassName
  2. Student : StudentID-FirstName-Surname
  3. StudentClass : StudentID-ClassID

After adding all the relationship and updated the model via model browser I have noticed that StudentClass does not appear, this seems to be default behaviour.

Now I need to do both an Insert and Update. How do you do it? Any code samples or link where I can download an example, or can you spare 5 mins?

like image 257
user9969 Avatar asked Nov 23 '10 05:11

user9969


1 Answers

In terms of entities (or objects) you have a Class object which has a collection of Students and a Student object that has a collection of Classes. Since your StudentClass table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.

Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the Class object, the Student objects, add the students to the class Students collection add the Class object to the context and call SaveChanges:

using (var context = new YourContext()) {     var mathClass = new Class { Name = "Math" };     mathClass.Students.Add(new Student { Name = "Alice" });     mathClass.Students.Add(new Student { Name = "Bob" });      context.AddToClasses(mathClass);     context.SaveChanges(); } 

This will create an entry in the Class table, two entries in the Student table and two entries in the StudentClass table linking them together.

You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call SaveChanges. Check this similar question for details.

Edit:

According to your comment, you need to insert a new Class and add two existing Students to it:

using (var context = new YourContext()) {     var mathClass= new Class { Name = "Math" };     Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");     Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");     mathClass.Students.Add(student1);     mathClass.Students.Add(student2);      context.AddToClasses(mathClass);     context.SaveChanges(); } 

Since both students are already in the database, they won't be inserted, but since they are now in the Students collection of the Class, two entries will be inserted into the StudentClass table.

like image 86
Yakimych Avatar answered Sep 22 '22 06:09

Yakimych