2012-12-13 157 views
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时,字段被正确填充,复选框也被正确检查。 我更改值(字符串和整数)以及复选框并保存。

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

我在做什么错?

回答

0

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

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

+0

实体框架为我们创建了一个联结表。除了更新以外,每件事情都可以。交界表是什么似乎没有得到更新。 –