MigrateDatabaseToLatestVersion no running Seed() method

后端 未结 1 1988
孤独总比滥情好
孤独总比滥情好 2021-02-14 08:00

I\'m trying to automatically generate my database if it doesn\'t exists and run the Seed() method to populate the data. In my Database Context constructor I have th

1条回答
  •  滥情空心
    2021-02-14 08:18

    I ended up with this Configuration class:

    public class Configuration : DbMigrationsConfiguration
        {
            private readonly bool _pendingMigrations;
    
            public Configuration()
            {
                AutomaticMigrationsEnabled = true;
    
                // Check if there are migrations pending to run, this can happen if database doesn't exists or if there was any
                //  change in the schema
                var migrator = new DbMigrator(this);
                _pendingMigrations = migrator.GetPendingMigrations().Any();
    
                // If there are pending migrations run migrator.Update() to create/update the database then run the Seed() method to populate
                //  the data if necessary
                if (_pendingMigrations)
                {
                    migrator.Update();
                    Seed(new Context.MyDBContext());
                }
            }
    
            protected override void Seed(Context.MyDBContext context)
            {
                // Microsoft comment says "This method will be called after migrating to the latest version."
                // However my testing shows that it is called every time the software starts
    
                // Run whatever you like here
    
                // Apply changes to database
                context.SaveChanges();
                base.Seed(context);
            }
        }
    

    So on this way the Seed() method is called when the database is created and also when there are pending migrations.

    This is my MyDBContext class:

    public class MyDBContext: DbContext
    {
        public MyDBContext() : base(AppSettings.DBConnectionString)
        {
        }
    
        public static MyDBContext Create()
        {
            return new MyDBContext();
        }
    
        public DbSet Users { get; set; }
        public DbSet Entries { get; set; }
    }
    

    0 讨论(0)
提交回复
热议问题