Entity Framework, Automatic apply Migrations

后端 未结 4 531
后悔当初
后悔当初 2020-12-08 05:26

I am using Entity Framework Code First approach with AutomaticMigrationsEnabled = true:

Database.SetInitializer(new MigrateDatabaseToLatestVersi         


        
4条回答
  •  时光说笑
    2020-12-08 06:16

    Automatic Migrations means that you don't need to run add-migration command for your changes in the models, but you have to run update-database command manually.

    If Automatic Migrations is enabled when you call update-database, if there are pending changes in your models, an 'automatic' migration will be added and database will be updated.

    If you want that your database is updated without need to call update-database command, you can add Database.SetInitializer(...) in OnModelCreating() method on your context, like so:

    public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion());
        }
    
        ...
    }
    
    public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration
    {
        ...
    

    Note that you should declare DbMigrationsConfiguration and MigrateDatabaseToLatestVersion with your real context, not the default DbContext.

提交回复
热议问题