Question

I would like to introduce Code First Migrations to my project, but I am unsure of how to handle deploying this to my client for testing. Until now, things have been quite simple, and I have just used a CreateDatabaseIfNotExists initializer. Now, I have two scenarios:

  1. He deletes his existing, before-migrations, database, and uses an initializer to create a new, with-migrations, database, and we use migrations from here on to upgrade his database. Can I use the MigrateDatabaseToLatestVersion initializer to create the DB if missing as well?

  2. I just deploy my code and let it perform migrations. I'm not quite sure if anything but using a MigrateDatabaseToLatestVersion is required here. Will this upgrade a pre-migrations database to one suitable for migrations?

Was it helpful?

Solution

This is what I do when automatic migration is required; I hope this helps you find a solution:

Database.SetInitializer(
    new MigrateDatabaseToLatestVersion<ContextFileName, PathToMigrationsConfig>()
    );
Database.Initialize(false);

In the configuration file for the migrations, I set the following in the constructor

AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;

In the configuration file you should have an override of the seed method, if not you can add it and fill in your seed data.

What the above will do is create/upgrade the database to the latest as long as no data loss occurs. This should allow you hand off the code to the client.


On a side note, for a production system I will usually argue the point of not doing this. This had many disadvantages. For databases I do not have control over I have yet to find a client that has refused the generated script file.

You can get this by using the following command after you add a migration through the Package Manager Console:

Update-database –script -verbose
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top