MVC3 code first: migrations and generating the database

1.9k Views Asked by At

I'm a bit lost how I should get the entity framework to work with automatic migration. I want:

  • The database to be created automatically when it doesnt exist
  • The database to be updated automatically when the model changed

For the latter I'm using DbMigrator. It is rather slow so I don't want to run it every request, and also I have multiple databases in the same application so it cant go in Application_Start which is why I put it in Session_Start like this:

    if (Session["started"] == null)
    {
        // this takes care of any database updates that might be necessary. 
        MigrationConfiguration configuration = new MigrationConfiguration();
        DbMigrator migrator = new DbMigrator(configuration);
        List<string> pm = migrator.GetPendingMigrations().ToList();
        if (pm.Count > 0)
        {
            migrator.Update();
        }
    }
    else
    {
        Session["started"] = "started";
    }

Not sure if this is the right way to do it but it seems to work, however it doesnt actually generate the database when it doesnt exist. It gives me a "Cannot open database "db" requested by the login"

I had this working before with the following:

    Database.SetInitializer<DbContext>(new InitializerIfModelChange());

This drops the database and generates seed data which is fine for when the database doesnt exist but it also is triggers when the database is changed (in which case I would like DbMigrator to handle it) This was in Application_Start before but I'm not sure what to do with it. I'm afraid that it will conflict with the DbMigrator. How would I set this all up in order to achieve the two things described earlier?

1

There are 1 best solutions below

0
On

I manually run the Update-Database in the package manager whenever the database needs to be changed. Initially I used the Database.SetInitializer like you did to create the database but have it commented out now.

Checkout Entity Framework 4.3 Automatic Migrations Walkthrough for more advanced help.

This should work for what you want, then if you need to create a new database just add Database.SetInitializer<NewDBContext>(new NewDBInitializer()); like you had, build and run. Then comment it out so it doesn't run in the future on a model change and instead use the Update-Database command in the package manager.