实体框架:使用现有数据(种子)填充多对多关系

时间:2018-04-17 12:19:35

标签: entity-framework ef-code-first ef-migrations seeding

在我的Code-First数据库中,我在对象"问题"之间存在多对多的关系。对象" Section",注意如下: 在章节中:

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

问题:

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

这会在两者之间创建一个名为QuestionSections的链接表。 但是,当我尝试运行种子方法时,链接表不会被填充。

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

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

创建问题,创建部分,但不填充链接表。 我已检查对象section1,section2和section3是否已启动并填充,它们是。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您还必须将相似的代码写入Link表。 questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x));因为当您致电context.SaveChanges();时,DBContext不知道此链接表。