我有一个向导步骤,用户填写字段。然后我使用json将值保存到我的数据库中,用于每个向导步骤。 但是,在我的存储库中,我有我的savechanges()。但它不会保存更改,而是会抛出错误:
'NKImodeledmxContainer.SelectedQuestion'中的实体参与'QuestionSelectedQuestion'关系。找到0个相关的“问题”。 1'问题'是预期的。
任何人都知道如何摆脱错误?我是否必须从问题中获取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();
}
}
这是我的ViewModel:
public class SelectedQuestionViewModel
{
public int? Grade { get; set; }
public string Comment { get; set; }
public string SelectedQuestionText { get; set; }
public int QuestionID { get; set; }
}
这是我的数据库模型:
答案 0 :(得分: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);
}