2012-04-24 179 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