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) { //... }動作します。URL を開くと/Edit/1、フィールドが適切に入力され、チェック ボックスも適切にチェックされます。値 (文字列と整数) を変更し、チェック ボックスも変更して保存します。

次に、チェックボックスは更新されていませんが、他の値は更新されていることに気付きました。

私は何を間違っていますか?

4

1 に答える 1

0

ジャンクション テーブルhttp://en.wikipedia.org/wiki/Junction_tableを使用して、多対多の関係を回避してみてください。

問題は、システムが多対多の関係を好まないことにあるかもしれません。

于 2012-12-13T17:27:46.337 に答える