It's weird, but all answers here were useless for me. For me worked initializer
MigrateDatabaseToLatestVersion
Here's my solution (I know, it can be much simplier, but it's how I use it):
class MyDbMigrateToLatest : MigrateDatabaseToLatestVersion<MyDbContext, Configuration>
{
}
public class MyDbContext: DbContext
{
public MyDbContext() : base("DbName")
{
SetInitializer();
}
public MyDbContext(string connString) : base(connString)
{
SetInitializer();
}
private static void SetInitializer()
{
if (ConfigurationManager.AppSettings["RebuildDatabaseOnStart"] == "true")
Database.SetInitializer(new MyDbInitializerForTesting());
else
Database.SetInitializer(new MyDbMigrateToLatest());
}
}
public sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyDbContext context)
{
// Whatever
}
}
MyDbInitializerForTesting just inherits from DropCreateDatabaseAlways so in some specific case (testing), whole database is rebuilded. Otherwise it's migrated to latest version.
My source: https://msdn.microsoft.com/en-us/data/jj591621.aspx#specific