0

我正在开发一个涉及多对多关系的 MVC 4 互联网应用程序。我设法建立了多对多关系,但我无法更新它。

public class Machine
{
    public int ID { get; set; }

    //Other attributes

    public List<Task> Tasks {get; set; }
}

public class Task
{
    public int ID { get; set; }

    //other attributes

    public List<Machine> Machines { get; set; }
}

我创建了一些示例数据,就我而言,映射工作正常。

然后我继续创建 CURD。我想添加一个复选框列表,用于为“添加/编辑机器”视图选择任务。

class MachineController : Controller
{
  public ActionResult Add(){ return View(); }

  [HttpPost]
  public ActionResult Add(Machine machine, string[] tasks)
  {
    //some code here
  }

  public ActionResult Edit(int id) { //some code here } 

  [HttpPost]
  public ActionResult Edit(Machine machine, string[] tasks)
  {
    //This method will add or remove Task objects from the list as needed & works
    UpdateMachineTasks(machine, tasks);
    //The below method fails - exception: 
        //An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
    //db.Entry(machine).State = EntityState.Modified
    //Then I used the following from a post I found on SO
    Machine m = db.Machines.Find(machine.ID);
    db.Entry(m).CurrentValues.SetValues(machine) //On debug, `machine` has the proper `Task` 
    db.SaveChanges();
  }
}

Add(Machine machine, string[] tasks) { //... }作品很好。当我打开网址/Edit/1时,字段已正确填充,并且复选框也已正确选中。我更改值(字符串和整数)以及复选框并保存。

然后我注意到复选框没有更新,但其他 vlues 是。

我究竟做错了什么?

4

1 回答 1

0

尝试使用联结表http://en.wikipedia.org/wiki/Junction_table来解决您的多对多关系。

问题可能是您的系统不喜欢多对多关系。

于 2012-12-13T17:27:46.337 回答