others - 由于另一个实体有相同的key-value,因此 C#添加实体失败

这是控制器编辑


 // 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;


 }



时间:

解决方案是从基础检索对象,这将使Entity Framework知道并在上下文中管理对象。然后,必须获取从视图中更改,并由实体控制的对象中的每个值。


// 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<Category, Category>();



Mapper.Map<Category, Category>(categoryFromViewModel, categoryFromBase);


Repository.Save(categoryFromBase); 




Mapper.Map<Category, Category>(categoryFromViewModel, categoryFromBase);



我认为以下是你想要的:


Category categoryFromBase = Mapper.Map<Category>(categoryFromViewModel)



...