I've been wracking my brain over this for a few days and have tried many "fixes", but all to no avail.
I'm using MVC4 with EF Code first, and the repository pattern on a many-to-many relationship. The tables are created correctly as far as I can tell as when I seed the database, my displaying shows the values correctly.
Where I have issue is when trying to save an Edit. I have an Edit View, with a Listbox containing an enumerated set of objects (B's) and on the Submit (HttpPost), I want to essentially call A.ClassBs.Clear() and db.SaveChanges(). However when I do this, ClassA.ClassBs is not blank.
If, for example, I update another property from A, I have to include db.Entry(ClassA).State = EntityState.Modified before db.SaveChanges() or else the change is not saved to the database.
When I include the EntityState.Modified line, ClassA updates as expected, with the exception of the many-to-many relationship. The ClassA.ClassBs are unchanged.
Here's some
Models
class A
{
...
virtual IEnumerable<ClassB> ClassBs {get;set;}
}
class B
{
...
virtual IEnumerable<ClassA> ClassAs {get;set;}
}
Controller
public ActionResult Edit(int id - 0)
{
... (create viewmodel)
return View(viewmodel)
}
[HttpPost]
public ActionResult Edit(viewmodel)
{
viewmodel.A.ClassBs.Clear();
db.Entry(viewmodel.A).State = EntityState.Modified;
db.SaveChanges();
}
View
@Html.ListBoxFor(model => model.ClassA.ClassBs, Model.ClassBs)
Something odd is going on with my binding. What am I doing wrong?