Entity Framework:使用现有数据填充多对多关系(种子)

Entity Framework: Populating a many-to-many relationship with existing data (seed)

在我的 Code-First 数据库中,对象 "Question" 和对象 "Section" 之间存在多对多关系,注释如下: 在部分:

public List<Question> Questions { get; set; }

问题:

public List<Section> Sections { get; set; }

这确实在两者之间创建了一个 link table,称为 QuestionSections。 但是,当我尝试 运行 我的种子方法时,link table 不会被填充。

种子方法相关部分代码如下:

var Sections = new List<Section>
{
    new Section
    {
        InternalSectionId = 1,
        Name = "Global information",
        SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
    },
    new Section
    {
        InternalSectionId = 2,
        Name = "More specific",
        SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
    },
    new Section
    {
        InternalSectionId = 3,
        Name = "TestingSection",
        SurveyId = context.Surveys.First(s => s.Title == "Test Survey").Id
    }
};
Sections.ForEach(x => context.Sections.AddOrUpdate(ss => ss.Name, x));
context.SaveChanges();

List<Section> section1 = context.Sections.Where(sect => sect.InternalSectionId == 1 && sect.SurveyId == 1)
    .ToList();
List<Section> section2 = context.Sections.Where(sect => sect.InternalSectionId == 2 && sect.SurveyId == 1)
    .ToList();
List<Section> section3 = context.Sections.Where(sect => sect.InternalSectionId == 3 && sect.SurveyId == 1)
    .ToList();

var questions = new List<Question>
            {
                new Question
                {
                    Sections = section1,
                    Title = "What is 1+1?",
                    QuestionOrderId = 1,
                    AnswerRequired = true,
                    InputTypeId = context.InputTypes.First(ip => ip.VisibleName.Equals("Dropdownbox")).Id,
                    StorageType = (int)Constants.Constants.StorageTypes.BoolType
                },
                new Question
                {
                    Sections = section2,
                    Title = "What is 2/1?",
                    QuestionOrderId = 1,
                    AnswerRequired = true,
                    InputTypeId = context.InputTypes.First(ip => ip.VisibleName.Equals("Text")).Id,
                    StorageType = (int)Constants.Constants.StorageTypes.IntType
                    }
                }
            }
questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x));
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();

问题已创建,部分已创建,但 link table 未填充。 我检查了对象 section1、section2 和 section3 是否已启动和填充,它们是。

我做错了什么?

您还必须编写与 Link table 类似的代码。 questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x)); 因为当您调用 context.SaveChanges();.

时,DBContext 不知道这个 link table