附加类型的实体失败,因为相同类型的另一个实体已具有相同的主键值。

让我快速描述一下我的问题。

我有5个客户的5个数据库每个 数据库 都有一个名为SubnetSettings的表

我已经创建了一个下拉列表来选择一个客户,并将显示属于所选客户的SubnetSetting表,并允许我创建,编辑和删除。

我可以创建,删除没有问题, 但当我想编辑数据时,它会带来错误:

‘/ TMS’应用程序中的服务器错误。

附加“CFS.Domain.Entities.SubnetSettings”类型的实体失败,因为同一类型的另一个实体已具有相同的主键值。 如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。 这可能是因为某些实体是新的并且尚未收到数据库生成的键值。 在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。

这是我的控制器中的编辑

// GET: /SubnetSettings/Edit1/5 public ActionResult Edit1(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SubnetSettings subnetsettings = detailView.SubnetSettings.SingleOrDefault(t => t.Id == id); if (subnetsettings == null) { return HttpNotFound(); } return View(subnetsettings); } // POST: /SubnetSettings/Edit1/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit1([Bind(Include = "Id,Name,fDialUp,fPulse,fUseExternalGSMModem,fGsmDialUp,bUploadMethodId")] SubnetSettings subnetsettings) { if (ModelState.IsValid) { templateDb2.Save(subnetsettings); return RedirectToAction("Index"); } return View(subnetsettings); } 

这是EF中的Save方法

  public SubnetSettings Save(SubnetSettings subnetsettings) { if (subnetsettings.Id == 0){ context.SubnetSettings.Add(subnetsettings); } else { context.SubnetSettings.Attach(subnetsettings); context.Entry(subnetsettings).State = EntityState.Modified; } context.SaveChanges(); return subnetsettings; } 

我知道很难理解其他人的代码。 所以任何建议或建议都非常感谢。

客观地合成答案:您尝试更新的对象不是来自基础,这是错误的原因。 该对象来自View的post。

解决方案是从base检索对象,这将使Entity Framework知道并管理上下文中的对象。 然后,您必须从View查看已更改的每个值,并包含在Entity控制的对象中。

 // POST: /SubnetSettings/Edit1/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit1([Bind(Include = "Id,Name,fDialUp,fPulse,fUseExternalGSMModem,fGsmDialUp,bUploadMethodId")] SubnetSettings subnetsettings) { if (ModelState.IsValid) { //Retrieve from base by id SubnetSettings objFromBase = templateDb2.GetById(subnetsettings.Id); //This will put all attributes of subnetsettings in objFromBase FunctionConsist(objFromBase, subnetsettings) templateDb2.Save(objFromBase); //templateDb2.Save(subnetsettings); return RedirectToAction("Index"); } return View(subnetsettings); } 

要删除错误,我使用AutoMapper将视图模型对象复制到基础对象中,然后再进行更新。

 Category categoryFromBase = Repository.GetById(categoryFromViewModel.Id); Mapper.CreateMap(); Mapper.Map(categoryFromViewModel, categoryFromBase); Repository.Save(categoryFromBase); 

我不确定以下行是否按照您的意图行事:

 Mapper.Map(categoryFromViewModel, categoryFromBase); 

我想以下是你想要的:

 Category categoryFromBase = Mapper.Map(categoryFromViewModel)