使用外键插入多个值

时间:2014-09-04 10:31:19

标签: c# linq entity-framework

我有两张桌子 enter image description here

questionId是问题ID的外键。

我正在尝试在“答案”表格中保存4个答案。标题是问题的标题,它必须有4个答案。

enter image description here

如何插入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();

但使用此我只能插入一个值。我该如何解决?

2 个答案:

答案 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();