當我運行下面的代碼,我得到實體框架失敗,因爲相同類型的另一個實體已具有相同的主鍵值。外鍵
try {
var questionRepo = new QuestionRepository(db);
var question = new Question();
question.QuestionText = text;
question.QuestionCategory = SelectedQuestionCategory;
db.QuestionCategory.Attach(SelectedQuestionCategory);
//Tried adding
//db.Entry(question).State = System.Data.Entity.EntityState.Added;
questionRepo.Add(question);
db.SaveChanges();
} catch (Exception ex) {
Debug.WriteLine(ex.Message);
return;
}
沒有錯誤,當我以前沒有使用過的QuestionCategory
,但我得到一個錯誤,如果我有。
該錯誤僅在我已經在我的數據庫中選擇SelectedQuestionCategory
時有問題。我再次檢查了數據庫,Question
的主鍵位於id
列,而不是QuestionCategory
。
我得到的錯誤是:
附加型「QuestionCategory」的實體失敗 因爲同類型的另一實體已經具有相同的主 鍵值。
爲什麼它在等外鍵上失敗,而外鍵不是組合主鍵或主鍵?
SelectedQuestionCategory是通過下拉菜單{binding} wpf查看的值。 –
研究如何創建這些實例,並確保在您從數據庫中提取這些實例時,您沒有使用.AsNotTracking()來跟蹤它們。 – richardsonmarkj