Insert/Update Entity Framework for Many to Many How do I go about doing it?

c# entity-framework many-to-many

Question

I'm new to utilizing EF4 and I use it. I am having trouble inserting or updating a many to many in my project. I constructed a little project only for coding purposes.

Assume I have three tables.

  1. class: classname-classid
  2. Student ID, First Name, Last Name
  3. StudentID-ClassID: StudentClass

I observed that StudentClass does not display after adding every connection and updating the model using the model browser; this seems to be the normal behavior.

I must now do both an Insert and an Update. What is your method? Can you spare five minutes? Do you have any code examples or a website where I can obtain an example?

1
102
3/4/2016 8:05:54 AM

Accepted Answer

You have a variety of entities (or things) available.Class a thing that contains a collection ofStudents and aStudent a thing that contains a collection ofClasses Given yourStudentClass EF does not create an entity for the joining table since it just includes Ids and no other data. That is the proper conduct, and that is what you anticipate.

Try to think about objects now while doing inserts or changes. Create the class with two students, for instance, if you wish to insert one.Class item, theStudent Add the students to the class and the objectsStudents gathering adding theClass object to the call and contextSaveChanges :

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

An entry will be made in theClass two entries in the tableStudent two entries in the tableStudentClass table that connects them.

Updates are largely handled in the same way. Simple data retrieval, graph modification (by adding and deleting items from collections), and callSaveChanges See This question is related for further information.

Edit:

Your remark indicates that you should add a newClass plus two already existentStudents 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();
}

Both students won't be entered since they are already in the database, but because they are now in theStudents gathering of theClass two entries will be added to the list.StudentClass table.

137
5/23/2017 12:10:43 PM

Popular Answer

For updating, try this:

[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
    //get current entry from db (db is context)
    var item = db.Entry<Models.MathClass>(mathClassModel);

    //change item state to modified
    item.State = System.Data.Entity.EntityState.Modified;

    //load existing items for ManyToMany collection
    item.Collection(i => i.Students).Load();

    //clear Student items          
    mathClassModel.Students.Clear();

    //add Toner items
    foreach (var studentId in mathClassModel.SelectedStudents)
    {
        var student = db.Student.Find(int.Parse(studentId));
        mathClassModel.Students.Add(student);
    }                

    if (ModelState.IsValid)
    {
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(mathClassModel);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow