我有三个通过外键连接的表。我试图在问题表中插入1行,在另外两个表中插入两行。我收到错误'插入语句与外键约束冲突' 提前感谢您的帮助
diff
答案 0 :(得分:2)
听起来您的问题ID是自动生成的。在这种情况下
int questionId = questionObj.QuestionID;
仅在SaveChanges()
来电后才能使用。
通常,如果您有一个带有外键的EntitySet,则更容易使用导航属性而不是自己构建id引用。
Question questionObj = new Question();
questionObj.CreatedBy = "Test";
questionObj.CreatedDate = DateTime.Now;
QuestionRespons questionResponsesObj = new QuestionRespons();
// fill question response here
questionObj.QuestionResponses.Add(questionResponseObj);
Response responseObj = new Response();
// fill your response here
questionResponsesObj.Response = reponseObj;
// if you do the above in your loop you should be fine
testEntity.Questions.Add(questionObj);
testEntity.SaveChanges();
符合您的示例:
public void setMultiAnswer()
{
try
{
string question = "Question 1"
responsesList.Add("Answer1");
responsesList.Add("Answer2");
questionResponsesList.Add(false);
questionResponsesList.Add(true);
using (Entities testEntity = new Entities())
{
Question questionObj = new Question();
questionObj.Question1 = question;
questionObj.CreatedBy = "Test";
questionObj.CreatedDate = DateTime.Now;
testEntity.Questions.Add(questionObj);
for (int i = 0; i < responsesList.Count; i++)
{
// i am not sure about your relation here, but i assume you require one QuestionResponse per response
// which is why a moved the line of code
QuestionRespons questionResponsesObj = new QuestionRespons();
questionObj.QuestionResponses.Add(questionResponsesObj);
Response responseObj = new Response();
responseObj.Response1 = responsesList.ElementAt(i);
responseObj.CreatedBy = "Test";
responseObj.CreatedDate = DateTime.Now;
if (!string.IsNullOrEmpty(responseObj.Response1))
{
questionResponsesObj.Response = responseObj;
questionResponsesObj.CorrectResponse = questionResponsesList.ElementAt(i);
}
}
testEntity.SaveChanges();
}
}
catch (Exception ex)
{
Console.Write(ex);
}
}
答案 1 :(得分:1)
更改
的顺序int questionId = questionObj.QuestionID;
testEntity.SaveChanges();
进入
testEntity.SaveChanges();
int questionId = questionObj.QuestionID;
您创建了一个新实例questionObj
,其默认ID应为0。
只有在调用SaveChanges()
之后,才应为ID分配新分配的实际ID值。
因此,这里发生的是,您使用默认值questionId
而不是真实ID记住0
。作为一个结果,问题和答案之间的关系总是错误的。
答案 2 :(得分:1)
如果我是你,我会删除这个QuestionResponse表,只保留问题和答案。使用导航属性而不是直接设置外键。
Question questionObj = new Question
{
Text = question,
CreatedBy = "Test",
CreatedDate = DateTime.Now
};
foreach(var response in responsesList.Where(x => !string.IsNullOrEmpty(x)))
{
Response responseObj = new Response
{
Text = response,
IsCorrect = true,
CreatedBy = "Test",
CreatedDate = DateTime.Now
}
questionObj.Add(responseObj);
}
testEntity.Questions.Add(questionObj);
testEntity.SaveChanges();