种子数据:迁移数据库时的初始数据。
播种:EF Core 2.1+ 支持的创建初始数据的方法。
推荐通过扩展方法,将创建种子数据的方法与 DbContext 解耦:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Seed();
}
}
public static class ModelBuilderExtensions
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasData(
new Student
{
Id = 1,
Name = "ltm",
ClassName = ClassNameEnum.FirstGrade,
Email = "ltm@ddxc.org"
},
new Student
{
Id = 2,
Name = "角落的白板报",
ClassName = ClassNameEnum.GradeThree,
Email = "werltm@qq.com"
});
}
}