questionId是问题ID的外键。
我正在尝试在“答案”表格中保存4个答案。标题是问题的标题,它必须有4个答案。
如何插入4通过外键连接的答案?
我试过这个:
QuizEntities quiz = new QuizEntities();
Question question = new Question();
Answer answer = new Answer();
question.Title = titleBox.Text;
question.ImageURL = "../Uploads/" + PhotoBox.Text;
answer.Answer1 = firstAnswer.Text;
answer.Answer1 = secondAnswer.Text;
answer.Answer1 = thirdAnswer.Text;
answer.Answer1 = fourthAnswer.Text;
answer.questionId = question.Id;
if (firstCheckBox.Checked)
{
answer.IsCorrect = true;
}
else
{
answer.IsCorrect = false;
}
quiz.Questions.Add(question);
quiz.Answers.Add(answer);
quiz.SaveChanges();
但使用此我只能插入一个值。我该如何解决?
答案 0 :(得分:3)
只需创建四个答案并将它们全部插入,您就可以创建一个函数来使代码更具可读性。
private static Answer CreateAnswer (
int id, string answer, bool isCorrect, int questionId)
{
var answer = new Answer
{
Id = id,
Answer = answer,
IsCorrect = isCorrect,
questionId = questionId
};
return answer;
}
然后通过分配临时密钥为问题添加问题。
using (var quiz = new QuizEntities())
{
var qId = 1;
var question = new Question
{
Id = qId,
title = titleBox.Text,
ImageURL = "../Uploads/" + PhotoBox.Text
};
quiz.Questions.Add(question);
quiz.Answers.Add(
CreateAnswer(1, firstAnswer.Text, (bool)firstCheckBox.Checked, qId));
quiz.Answers.Add(
CreateAnswer(2, secondAnswer.Text, (bool)secondCheckBox.Checked, qId));
quiz.Answers.Add(
CreateAnswer(3, thirdAnswer.Text, (bool)thirdCheckBox.Checked, qId));
quiz.Answers.Add(
CreateAnswer(4, fourthAnswer.Text, (bool)fourthCheckBox.Checked, qId));
quiz.SaveChanges();
}
提示:
答案 1 :(得分:2)
如果您想准确添加四个值,则需要创建四个Answer
个对象,并为每个对象分配正确的问题ID。
如果不使用编译器对此进行测试,我认为您正在寻找类似的东西;
QuizEntities quiz = new QuizEntities();
Question question = new Question();
Answer answer = new Answer();
question.Title = titleBox.Text;
question.ImageURL = "../Uploads/" + PhotoBox.Text;
quiz.Questions.Add(question);
//Add first answer.
answer.Answer = firstAnswer.Text;
if (firstCheckBox.Checked)
{
answer.IsCorrect = true;
}
else
{
answer.IsCorrect = false;
}
answer.questionId = question.Id;
quiz.Answers.Add(answer);
//Add second answer.
answer = new Answer();
answer.Answer = secondAnswer.Text;
if (secondCheckBox.Checked)
{
answer.IsCorrect = true;
}
else
{
answer.IsCorrect = false;
}
answer.questionId = question.Id;
quiz.Answers.Add(answer);
//... add third and fourth as well.
quiz.SaveChanges();