Reputation: 914
This a ASP.NET MVC with Entity Framework 6.1 Code First application.
I need my application to CREATE the database if it doesn't exists and seed the tables with some data. Also I need to Migrate the database on application start if the model has changed using MigrateDatabaseToLatestVersion.
On the Application_Start i have:
protected void Application_Start()
{
Database.SetInitializer(new MyAppDataInitializer());
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyAppDataContext, MyApp.Model.Migrations.Configuration>());
}
The initializer:
public class MyAppDataInitializer: CreateDatabaseIfNotExists<MyAppDataContext>
{
protected override void Seed(MyAppDataContext context)
{
Code to add some "CREATION DATA"
}
}
Here is the Migration Configuration class:
public class Configuration : DbMigrationsConfiguration<MyApp.Model.DataContext.MyAppDataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "MyApp.Model.DataContext.MyAppDataContext";
}
protected override void Seed(MyApp.Model.DataContext.MyAppDataContext context)
{
Code to add some "MIGRATION DATA"
}
}
When my application starts it works as expected except for one thing:
If the database exists, it works perfect, it changes the database according to the new model and it seeds the database with the "MIGRATION DATA".
If the database doesn't exists it creates the database but it only seeds the database with the "MIGRATION DATA" but not with the "CREATION DATA". The SEED method on the inicializer is not called.
I'm sure there is something I'm doing wrong here, but I can't figure out how can I create the database when it doesn't exists and seed some "init" data that it only insert for the first time.
Then when changing the model it only changes the database and add the data I setup in the migration seed method in case I need it.
Could you help me with this?
Thanks in advance.
Upvotes: 1
Views: 430
Reputation: 2569
You're overwriting the initializer. It's a "set" not an "add" initializer and there can only be one..
protected void Application_Start()
{
Database.SetInitializer(new MyAppDataInitializer());
// Now the initializer gets "re-set" again and MyAppDataInitializer is not used at all
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyAppDataContext, MyApp.Model.Migrations.Configuration>());
}
Upvotes: 1