我在更新edmx圖中不存在的多對多表格時遇到問題。更新多對多表格。 MVC中不存在表格
QuestionGroups
PK - QuesitonGroupID
Questions
PK - QuestionID
此表不EDMX存在:我無法更新這個表
QuestionGroupQuestions
PK - QuestionGroupID
PK - QuestionID
Answers
PK - AnswerID
這個表我能夠更新該表正確
QuestionAnswers
PK - QuestionID
PK - AnswerID
這裏代碼
public ActionResult Create(int questionGroupID, QuestionVM questionVM)
{
Mapper.CreateMap<Question, QuestionVM>();
Question question = Mapper.DynamicMap<Question>(questionVM);
if (question.Answers != null)
{
question.Answers = new List<Answer>();
foreach (var answer in questionVM.Answers)
{
var questionAnswerToAdd = db.Answers.Find(answer.AnswerID);
question.Answers.Add(questionAnswerToAdd);
}
}
db.Questions.Add(question);
db.SaveChanges();
var questionGroup = db.QuestionGroups.Find(questionGroupID);
questionGroup.Questions.Add(question);
db.QuestionGroups.Add(questionGroup);
上述代碼正在工作。我不想更新QuestionGroup表。我只想更新QuestionGroupQuestions表。
db.Entry(questionGroup).State = EntityState.Unchanged;
db.SaveChanges();
return RedirectToAction("Index", "Question");
}
更新前已經有2個現有記錄
QuestionGroupID, QuestionID
14,1
14,3
當添加一個新的問題,我得到這個錯誤信息
{「PRIMARY KEY約束的衝突‘PK_QuestionGroupQuestions’。不能插入在對象'dbo.QuestionGroupQuestions'中複製密鑰,複製密鑰值爲(14,1)。\ r \ n聲明已終止。「}
聽起來就像你已經與那個PK一行;沒有?你需要刪除這些? – ChiefTwoPencils 2015-04-05 02:32:08