Attaching an entity of type failed because another entity of the same type already has the same primary key value.

走远了吗. 提交于 2019-11-28 11:29:20
Allan Patrick Patzlaff

Synthesizing the answer objectively: The object you are trying to update don't came from the base, this is the reason of the error. The object came from the post of the View.

The solution is to retrieve the object from base, this will make Entity Framework know and manage the object in the context. Then you will have to get each value that has changed from View and consist in the object controlled by the 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);
}

To remove the error I used AutoMapper to copy the view model object into the base object, before Updating.

Category categoryFromBase = Repository.GetById(categoryFromViewModel.Id);
Mapper.CreateMap<Category, Category>();

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

I'm not sure the following line is doing what you intend:

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

I think the following is what you want:

Category categoryFromBase = Mapper.Map<Category>(categoryFromViewModel)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!