代码之家  ›  专栏  ›  技术社区  ›  Maarten B

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

  •  0
  • Maarten B  · 技术社区  · 7 年前

    在我的代码优先数据库中,对象“问题”和对象“部分”之间存在多对多关系,如下所示: 在第节中:

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

    问题:

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

    这会在这两个部分之间创建一个链接表,称为QuestionSections。 但是,当我尝试运行seed方法时,链接表不会被填充。

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

    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 回复  |  直到 7 年前
        1
  •  1
  •   Vivek Nuna Chetan sabhaya    7 年前

    您还必须编写类似的代码来链接表。 questions.ForEach(x => context.Questions.AddOrUpdate(q => q.Title, x)); 因为DBContext在调用时不知道这个链接表 context.SaveChanges();