2012-12-13 159 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

實體框架爲我們創建了一個聯結表。除了更新以外,每件事情都可以。交界表是什麼似乎沒有得到更新。 –