Confusion over EF Auto Migrations and seeding - seeding every program start

前端 未结 3 1714
渐次进展
渐次进展 2020-12-04 12:23

I recently changed an application from using the following for dev:

DropCreateDatabaseIfModelChanges


To using:

3条回答
  •  清歌不尽
    2020-12-04 12:49

    I somewhat agree with Arthur Vickers response, however IMO Seed is for DbMigrations and I don't want the Seed method to be checking everything every time, e.g. If I have 4 migrations then I would need to test somehow which data must be seeded and that will be 4 more database hits at least. In case you still would like to have the behavior of running Seed method only when migrations are applied, like me, I came with my own implementation of the IDatabaseInitializer strategy

    public class CheckAndMigrateDatabaseToLatestVersion
        : IDatabaseInitializer
        where TContext : DbContext
        where TMigrationsConfiguration : DbMigrationsConfiguration, new()
    {
        public virtual void InitializeDatabase(TContext context)
        {
            var migratorBase = ((MigratorBase)new DbMigrator(Activator.CreateInstance()));
            if (migratorBase.GetPendingMigrations().Any())
                migratorBase.Update();
        }
    }
    

提交回复
热议问题