我正在研究一个涉及多对多关系的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 :(得分:0)
尝试使用联结表http://en.wikipedia.org/wiki/Junction_table来解决您的多对多关系。
问题可能是您的系统不喜欢多对多关系。