简体   繁体   English

一次在Entity中插入多个相关表

[英]Insert multiple related tables in Entity at once

I have three tables that are connected by foreign keys. 我有三个表通过外键连接。 I am trying to insert 1 row in the question table and two rows in the other two tables. 我试图在问题表中插入1行,在另外两个表中插入两行。 I am getting the error 'Insert statement conflict with Foreign Key constraint' Thank you in advance for the help 我收到错误'插入语句与外键约束冲突'提前感谢您的帮助

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;

        QuestionRespons questionResponsesObj = new QuestionRespons();
        // fill response
        foreach (var questionResponse in questionResponsesList)
        {
            questionResponsesObj.CorrectResponse = questionResponse;
        }

        questionObj.QuestionResponses.Add(questionResponsesObj);

        Response responseObj = new Response();

        // fill response 
        foreach (var response in responsesList)
        {
             responseObj.Response1 = response;
             responseObj.CreatedBy = "test";
             responseObj.CreatedDate = DateTime.Now;
        }
        questionResponsesObj.Response = responseObj;

        testEntity.Questions.Add(questionObj);
        testEntity.SaveChanges();
    }
}
catch (Exception ex)
{
    Console.Write(ex);
}

It sounds like your question id is autogenerated. 听起来你的问题id是自动生成的。 In this case int questionId = questionObj.QuestionID; 在这种情况下int questionId = questionObj.QuestionID; will only work after the SaveChanges() call. 只有在SaveChanges()调用后才能工作。

In general if you have an EntitySet with foreign keys it is easier to use the navigation properties instead of building id references yourself. 通常,如果您有一个带有外键的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();

To match your example: 要匹配您的示例:

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);
    }
}

Change the order of 改变顺序

int questionId = questionObj.QuestionID;
testEntity.SaveChanges();

into

testEntity.SaveChanges();
int questionId = questionObj.QuestionID;

You created a new instance questionObj which should have a default ID of 0. Only AFTER calling SaveChanges() the ID should be assigned the newly assigned actual ID value. 您创建了一个新的实例questionObj ,其默认ID为0.只有在调用SaveChanges() ,才应为ID分配新分配的实际ID值。

So, what happens here, is that you memorize questionId with the default value of 0 instead of the real ID. 所以,这里发生的是你用默认值0而不是真实ID记住questionId As a conseqence, the relations between questions and responses will always be wrong. 作为一个结果,问题和答复之间的关系总是错误的。

If I were you I would remove this QuestionResponse table, to keep only Question and Response. 如果我是你,我会删除这个QuestionResponse表,只保留问题和答案。 Use the navigation properties instead of directly setting the foreign key. 使用导航属性而不是直接设置外键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM