I'm writing an ASP.NET MVC 2 application that uses Entity Framework 4 and WCF Data Services.
I want to manipulate the many-to-many (composite key) relationship between Duties and Workers based on the state of some checkboxes.
A Worker may have zero or more duties. A Duty may have zero or more workers.
This code is from one of my controllers:
//
// POST: /Duty/Edit/5
[HttpPost]
public ActionResult Edit(Duty Model, FormCollection collection)
{
ctx.AttachTo("Duties", Model);
ctx.UpdateObject(Model);
// handle checkboxes
ctx.LoadProperty(Model, "Workers");
foreach (Worker w in ctx.Workers)
{
bool isChecked = collection[w.Id.ToString()].Contains("t");
bool wasChecked = Model.Workers.Contains(w);
if (isChecked && !wasChecked)
{
Model.Workers.Add(w);
}
else if (wasChecked && !isChecked)
{
Model.Workers.Remove(w);
}
}
ctx.SaveChanges();
return RedirectToAction("Index");
}
The Add() and Remove() methods are called appropriately. This executes without exception. But, the changes don't get committed to my database. Why?
Update
I've tried flipping it around to w.Duties.Add(Model);
and that doesn't work either.