我在更新edmx图中不存在的多对多表时遇到问题。
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语句已终止。”}
答案 0 :(得分:0)
在映射具有多对多关系(QuestionGroups
和Questions
)的表时,包含相关ID(QuestionGroupQuestions
)的表不会映射到任何实体,而不是它另一个tow表映射到具有多对多关联的实体,该关联是其中相互实例的集合,当保存这些两个表的任何有效更改时,EF会自动更新第三个表({{1因此,不需要更新QuestionGroupQuestions。
QuestionGroupQuestions
现在如果将更改保存到var questionGroup = db.QuestionGroups.Find(questionGroupID);
questionGroup.Questions.Add(question);
//The problem is here that you are adding questionGroup again. comment it and check
//db.QuestionGroups.Add(questionGroup); this cause a error, questionGroup already exists
,QuestionGroupQuestions表也应该更新。