ObjectStateManager错误

时间:2011-07-13 11:15:33

标签: asp.net-mvc entity-framework-4

我有控制器后期行动

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();
    }
}

当我尝试更新时

public void Update(Proposal proposal)
{
    mContext.Proposals.ApplyCurrentValues(proposal);
}

抛出错误:在ObjectStateManager中找不到具有与提供的对象的键匹配的键的对象。验证提供的对象的键值是否与必须应用更改的对象的键值匹配。 我正在寻找解决方案,我发现了这个:

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();
    }
}

只添加一行:

Proposal proposal = proposalRepository.GetById(model.Proposal.ProposalID);

它运作良好,但我认为这是一个愚蠢的决定,我相信有更好的方法和解释???

1 个答案:

答案 0 :(得分:0)

这就是ApplyCurrentValues的工作原理。您必须首先加载实体才能使用它(=在修改附加实体时使用它)。如果您不想先加载,请将Update方法更改为:

public void Update(Proposal proposal)
{
    mContext.Proposals.Attach(proposal);
    mContext.ObjectStateManager.ChangeObjectState(proposal, EntityState.Modified);
}