Search code examples
linqwcfentity-frameworkmany-to-manywcf-data-services

WCF Data Service Many-to-Many Relationship with EF4


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.


Solution

  • Use methods AddLink and DeleteLink.

    //
    // POST: /Duty/Edit/5
    
    [HttpPost]
    public ActionResult Edit(Duty Model, FormCollection collection)
    {
        ctx.AttachTo("Duties", Model);
        ctx.UpdateObject(Model);
    
        // handle checkboxes
        foreach (Worker w in ctx.Workers.Expand("Duties"))
        {
            bool isChecked = collection[w.Id.ToString()].Contains("t");
            bool wasChecked = w.Duties.Contains(Model);
            if (isChecked && !wasChecked)
            {
                ctx.AddLink(Model, "Workers", w);
            }
            else if (wasChecked && !isChecked)
            {
                ctx.DeleteLink(Model, "Workers", w);
            }
        }
    
        ctx.SaveChanges();
        return RedirectToAction("Index");
    }
    

    See the Creating and Modifying Relationship Links section of MSDN article Updating the Data Service (WCF Data Services)