如何在.net c# EF中使用外键通过种子方法填充数据库,并在表之间创建关系

本文关键字:数据库 填充 子方法 种子 关系 创建 之间 EF net | 更新日期: 2023-09-27 18:13:08

我的种子方法包含如下内容:

        var professors = new List<Professor>
        {
            new Professor
            {
                Name = "Arturo Anand",
                EnrollmentDate = DateTime.Parse("09-08-2015")
            }
        };
        professors.ForEach(prof => context.Professors.AddOrUpdate(prof));
        context.SaveChanges();
        var presentations = new List<Presentation>
        {
            new Presentation
            {
                PresentationTitle = "Test",
                PresentationTime = DateTime.Parse("09-09-2015"),
                Level = Level.Advanced,
            }
        };
        presentations.ForEach(pres => context.Presentations.AddOrUpdate(pres));
        context.SaveChanges();

这是两个类之间的关系:展示类:

    public class Presentation
{
    public int PresentationId { get; set; }
    public string PresentationTitle { get; set; }
    public DateTime PresentationTime { get; set; }
    public Level? Level { get; set; }
    public virtual Professor Professor { get; set; }
}

类教授:

  public class Professor
{
    public int ProfessorId { get; set; }
    public string Name { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public virtual ICollection<Presentation> Presentations { get; set; }
}

我真的不知道我应该如何从种子方法填充数据库,以便将数据绑定到两个表的表单,以便在它们上创建CRUD操作。

编辑:教授模型:

    public class Professor
{
    public int ProfessorId { get; set; }
    public string Name { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public virtual ICollection<Presentation> Presentations { get; set; }
}

如何在.net c# EF中使用外键通过种子方法填充数据库,并在表之间创建关系

由于ProfessorsPresentation之间存在关系,您可以将演示文稿直接分配给教授对象,EF将为您填充FK。试试这个

protected override void Seed(yourDbContext context)
{
       var professors = new List<Professor>
       {
         new Professor
         {
            Id = 1,
            Name = "Arturo Anand",
            EnrollmentDate = DateTime.Parse("09-08-2015"),
            Presentations = new List<Presentation>
              {
                 new Presentation
                 {
                 PresentationTitle = "Test",
                 PresentationTime = DateTime.Parse("09-09-2015"),
                 Level = Level.Advanced,
                 }
              }
         }
     };
  //make sure to specify a key for the AddOrUpdate Method to ensure 
  //that you don’t create duplicates when you seed data during development.
   professors.ForEach(prof => context.Professors.AddOrUpdate(x => x.Id, prof));
}

也不需要调用SaveChanges。执行Update-Database命令将执行种子方法