How to manually (via code) apply DbMigration which was manually crafted?

c# dbmigrate entity-framework-6

Popular Answer

Because the migrations are cumulative and must be executed in order, it makes no sense to cherry-pick one to run alone. Thus, it would be wiser for you to do the equivalent ofupdate-database launch-time powershell command for applications.

To achieve it, we use the following code:

In theConfiguration.cs class function Object() { [native code] } (made when you created this fileenable-migrations )

AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;

then use the next technique when the app launches:

public static void ApplyDatabaseMigrations()
{
    //Configuration is the class created by Enable-Migrations
    DbMigrationsConfiguration dbMgConfig = new Configuration()
    {
        ContextType = typeof(MyDbContext) //+++++CHANGE ME+++++
    };
    using (var databaseContext = new MyDbContext()) //+++++CHANGE ME+++++
    {
        try
        {
            var database = databaseContext.Database;
            var migrationConfiguration = dbMgConfig;
            migrationConfiguration.TargetDatabase =
                new DbConnectionInfo(database.Connection.ConnectionString,
                                     "System.Data.SqlClient");
            var migrator = new DbMigrator(migrationConfiguration);
            migrator.Update();
        }
        catch (AutomaticDataLossException adle)
        {
            dbMgConfig.AutomaticMigrationDataLossAllowed = true;
            var mg = new DbMigrator(dbMgConfig);
            var scriptor = new MigratorScriptingDecorator(mg);
            string script = scriptor.ScriptUpdate(null, null);
            throw new Exception(adle.Message + " : " + script);
        }
    }
}
0
11/28/2016 7:51:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow