1

我有一个向导步骤,用户在其中填写字段。然后,我使用 json 将每个向导步骤的值保存到我的数据库中。但是,在我的存储库中,我有我的 savechanges()。但它不会保存更改,而是会引发错误:

“NKImodeledmxContainer.SelectedQuestion”中的实体参与“QuestionSelectedQuestion”关系。找到 0 个相关的“问题”。预计有 1 个“问题”。

任何人都知道如何摆脱错误?我是否必须从 Question 中获取 ID 并将其保存到我的数据库中,或者我可以在 EF 中更改某些内容以便不会抛出错误消息?

这是我在控制器中的帖子:

        [HttpPost]
    public JsonResult AnswerForm(int id, SelectedQuestionViewModel model)
    {
        bool result = false;
        var goalCardQuestionAnswer = new GoalCardQuestionAnswer();
        goalCardQuestionAnswer.SelectedQuestion = new SelectedQuestion();

        goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID;
        goalCardQuestionAnswer.Comment = model.Comment;
        goalCardQuestionAnswer.Grade = model.Grade;

            if (goalCardQuestionAnswer.Grade != null)
            {

                    answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer);
                    answerNKIRepository.Save();
                    result = true;
                    return Json(result);                   
            }

       answerNKIRepository.SaveQuestionAnswer(goalCardQuestionAnswer);
       answerNKIRepository.Save();

        return Json(result);
    }

我的仓库

    public class AnswerNKIRepository
{
    private readonly NKImodeledmxContainer db = new NKImodeledmxContainer();

    public List<SelectedQuestion> GetAllSelectedQuestionsByGoalCardId(int goalCardId)
    {
        return db.SelectedQuestion.Where(question => question.GoalCard.Id == goalCardId).ToList();
    }

    public void SaveQuestionAnswer(GoalCardQuestionAnswer goalCardQuestionAnswer)
    {
        db.GoalCardQuestionAnswer.AddObject(goalCardQuestionAnswer);
    }

    public void Save()
    {
        db.SaveChanges();
    }
}

这是我的视图模型:

 public class SelectedQuestionViewModel
{

    public int? Grade { get; set; }
    public string Comment { get; set; }
    public string SelectedQuestionText { get; set; }
    public int QuestionID { get; set; }
}

这是我的数据库模型:

在此处输入图像描述

4

1 回答 1

1

异常抱怨这SelectedQuestion.Question是必需的导航属性,但您没有在代码中设置此属性。尝试从存储库中按 Id 加载问题并将其设置为SelectedQuestion.Question参考:替换此行 ...

goalCardQuestionAnswer.SelectedQuestion.Id = model.QuestionID;

...经过...

goalCardQuestionAnswer.SelectedQuestion.Question =
    answerNKIRepository.GetQuestionById(model.QuestionID);

并在您的存储库中添加方法:

public Question GetQuestionById(int id)
{
    return db.Question.Single(q => q.Id == id);
}
于 2012-04-24T13:32:40.050 回答