编程语言
首页 > 编程语言> > C#-播出多对多数据

C#-播出多对多数据

作者:互联网

您好,我正在尝试为我的项目创建一些种子,但是在将多对多关系数据播种到数据库时遇到了问题.

我的数据库如下所示:

enter image description here

在TeacherSkills中,Teacher_ID和Skill_ID是其课程表的外键.

我的播种机看起来像这样

protected override void Seed(Ability_Examen_ASP.Models.AbilityDbContext context)
    {
        if (!context.Skills.Any())
        {
            context.Skills.Add(new Models.Skill { SkillName = "PHP" });
            context.Skills.Add(new Models.Skill { SkillName = "Java" });
            context.Skills.Add(new Models.Skill { SkillName = "Frans" });
            context.Skills.Add(new Models.Skill { SkillName = "Drupal" });
        }

        if (!context.Teachers.Any())
        {
            context.Teachers.Add(new Models.Teacher
            {
                FirstName = "Joris",
                LastName = "Hens",
                Campus = "Kruidtuin",
                Password = "testpass",
                Email = "Joris.Hens@"
            });
            context.Teachers.Add(new Models.Teacher
            {
                FirstName = "Anne",
                LastName = "Van Goetem",
                Campus = "Kruidtuin",
                Password = "testpass",
                Email = "Anne.Vangoetem@"
            });
            context.Teachers.Add(new Models.Teacher
            {
                FirstName = "Sofie",
                LastName = "Krekels",
                Campus = "De Ham",
                Password = "testpass",
                Email = "Sofie.Krekels@"
            });
            context.Teachers.Add(new Models.Teacher
            {
                FirstName = "Robby",
                LastName = "Vanelderen",
                Campus = "De Vest",
                Password = "testpass",
                Email = "Robby.Vanelderen@"
            });
        }

        if (!context.TeacherSkills.Any())
        {
            context.TeacherSkills.Add(new Models.TeacherSkill
            {
                Teacher_ID = 1,
                Skill_ID = 1,
            });
            context.TeacherSkills.Add(new Models.TeacherSkill
            {
                Teacher_ID = 1,
                Skill_ID = 4,
            });
            context.TeacherSkills.Add(new Models.TeacherSkill
            {
                Teacher_ID = 2,
                Skill_ID = 2,
            });
            context.TeacherSkills.Add(new Models.TeacherSkill
            {
                Teacher_ID = 3,
                Skill_ID = 3,
            });
            context.TeacherSkills.Add(new Models.TeacherSkill
            {
                Teacher_ID = 4,
                Skill_ID = 4,
            });
        }

    }

老师和技能的播种没有任何问题,但是我不能给老师播种任何技能.

它不会给我任何错误,而且我不确定是什么错误.

希望大家能帮忙,谢谢!

解决方法:

将通话添加到

context.SaveChanges();  

在您填补教师的位置和您将要播授教师技能的位置之间.这应该提交“技能和教师”集合,以便您对键列(标识值)的假设将被INSERT执行时实际生成的假设所取代.

此外,可以检索实际的教师和技能的ID值,并在TeacherSkills构造函数中使用该值,以消除Seed代码中的“魔术数字” 1-4.

标签:code-first,seeding,c,asp-net-mvc,entity-framework
来源: https://codeday.me/bug/20191027/1944974.html