ObjectStateManager error
I have controller post action
public ActionResult Demographics(string submitButton, DemographicsViewModel model)
{
switch (submitButton)
{
case "Home":
return RedirectToAction("Index");
case "Next Page":
using (ProposalRepository proposalRepository = new ProposalRepository())
{
model.Proposal.UserID = proposalRepository.GetUserByName(MasterHelper.CurrentUsername).UserID;
model.Proposal.CustomerID = proposalRepository.GetCustomerByName(model.CustomerName).CustomerID;
if (model.Proposal.ProposalID != 0)
{
proposalRepository.Update(model.Proposal);
}
else
{
proposalRepository.AddProposal(model.Proposal);
}
proposalRepository.SaveChanges();
}
return RedirectToAction("GRQuestions", model.Proposal);
default:
return View();
}
}
When I try to update
public void Update(Proposal proposal)
{
mContext.Proposals.ApplyCurrentValues(proposal);
}
throw error: An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object mat开发者_如何学Cch the key values of the object to which changes must be applied. I was looking for a solution and I found this:
public ActionResult Demographics(string submitButton, DemographicsViewModel model)
{
switch (submitButton)
{
case "Home":
return RedirectToAction("Index");
case "Next Page":
using (ProposalRepository proposalRepository = new ProposalRepository())
{
Proposal proposal = proposalRepository.GetById(model.Proposal.ProposalID);
model.Proposal.UserID = proposalRepository.GetUserByName(MasterHelper.CurrentUsername).UserID;
model.Proposal.CustomerID = proposalRepository.GetCustomerByName(model.CustomerName).CustomerID;
if (model.Proposal.ProposalID != 0)
{
proposalRepository.Update(model.Proposal);
}
else
{
proposalRepository.AddProposal(model.Proposal);
}
proposalRepository.SaveChanges();
}
return RedirectToAction("GRQuestions", model.Proposal);
default:
return View();
}
}
add only one row:
Proposal proposal = proposalRepository.GetById(model.Proposal.ProposalID);
It works well but I think this is a stupid decision and I believe there is a better way and an explanation???
That is how ApplyCurrentValues
works. You must load the entity first to use it (= it is used when modifying attached entity). If you don't want to load it first, change yourUpdate
method to:
public void Update(Proposal proposal)
{
mContext.Proposals.Attach(proposal);
mContext.ObjectStateManager.ChangeObjectState(proposal, EntityState.Modified);
}
精彩评论