2012-04-24 139 views
1

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

Entities in 'NKImodeledmxContainer.SelectedQuestion' participate in the 'QuestionSelectedQuestion' relationship. 0 related 'Question' were found. 1 'Question' is expected.

任何人都知道如何摆脱错误?我是否必须从问题中获取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; } 
} 

这是我的数据库模型:

enter image description here

+0

您没有在您的存储库中显示发生了什么,这可能是您问题中最重要的部分。 – 2012-04-24 12:57:53

+0

已更新至知识库 – 2012-04-24 13:00:56

回答

1

异常抱怨SelectedQuestion.Question是必需的导航属性,但您不在代码中设置此属性。尝试通过标识从存储库加载的问题,并将其设置为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); 
} 
+0

使用该代码我收到以下错误消息:“对象引用未设置为对象的实例” – 2012-04-24 13:40:04

+0

@ps__:代码的哪一行会出现此错误? – Slauma 2012-04-24 13:45:47

+0

在你建议我应该替换的那一行:“goalCardQuestionAnswer.SelectedQuestion.Question = answerNKIRepository.GetQuestionById(model.QuestionID);” – 2012-04-24 13:47:38