种子数据:迁移数据库时的初始数据。
    播种:EF Core 2.1+ 支持的创建初始数据的方法。

    推荐通过扩展方法,将创建种子数据的方法与 DbContext 解耦:

    1. public class AppDbContext : DbContext
    2. {
    3. public AppDbContext(DbContextOptions options) : base(options)
    4. {
    5. }
    6. public DbSet<Student> Students { get; set; }
    7. protected override void OnModelCreating(ModelBuilder modelBuilder)
    8. {
    9. modelBuilder.Seed();
    10. }
    11. }
    1. public static class ModelBuilderExtensions
    2. {
    3. public static void Seed(this ModelBuilder modelBuilder)
    4. {
    5. modelBuilder.Entity<Student>().HasData(
    6. new Student
    7. {
    8. Id = 1,
    9. Name = "ltm",
    10. ClassName = ClassNameEnum.FirstGrade,
    11. Email = "ltm@ddxc.org"
    12. },
    13. new Student
    14. {
    15. Id = 2,
    16. Name = "角落的白板报",
    17. ClassName = ClassNameEnum.GradeThree,
    18. Email = "werltm@qq.com"
    19. });
    20. }
    21. }