私は、多対多の関係を含む 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
、フィールドが適切に入力され、チェック ボックスも適切にチェックされます。値 (文字列と整数) を変更し、チェック ボックスも変更して保存します。
次に、チェックボックスは更新されていませんが、他の値は更新されていることに気付きました。
私は何を間違っていますか?