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

后端 未结 3 2057
深忆病人
深忆病人 2020-12-10 17:03

Let me quickly describe my problem.

I have 5 databases for 5 customers and each has the same table called SubnetSettings.

相关标签:
3条回答
  • 2020-12-10 17:56

    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)
    
    0 讨论(0)
  • 2020-12-10 17:57

    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);
    }
    
    0 讨论(0)
  • 2020-12-10 17:57

    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);   
    
    0 讨论(0)
提交回复
热议问题