您好,我正在尝试为我的项目创建一些种子,但是我无法将多对多关系数据播种到数据库中。
我的 数据库 如下所示:
在 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();
在您填补教师的位置和您将要播种教师技能的位置之间。这应该提交 Skills 和 Teachers 集合,以便您对键列(身份值)的假设将替换为执行 INSERT 时实际生成的假设。
此外,可以在教师技能构造函数中检索和使用实际教师和技能的 ID 值,以去除种子代码中的“魔数(Magic Number)”1-4。
关于c# - 播种多对多数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34640542/