Llm
Llm

Reputation: 147

EF 5 - Code first migrations optimization

I use Entity framework 5 code first with enabled migrations. I made many changes to my model classes and now I have too much migrations classes because after every change I updated the database. Now I want to merge all my updates to get one "initial class" or 2 so that I could run the update-database command only once if I have to create my database again. Is that possible with no code (too heavy), I mean with a command for instance ? Thanks.

Upvotes: 0

Views: 161

Answers (1)

The solution is based on whether you want to keep existing data in databases (if you have production databases this is definitely a must) or you can simply drop your database.

I. Cuurrent database can be droped

First you need to delete all migration steps and delete your current database then run the command

    add-migration Initial

This way you will have only one migration step instead of a lot.

II. Data must be kept

First create a backup of the current database (that is set as the default database in your solution), then drop the database so when you run the add-migration command the Entity Framework will think that no migrations were applied yet.

After this do the steps as described in the first part and then you will have only one migration step named Initial. After this run the

update-database

command which will create a database matching your current model however only with one row in the __MigrationHistory table. Save this row from the __MigrationHistory table.

Now you can restore the database you've just backed up, delete all rows in the __MigrationHistory table and insert that one row you have saved before. After this the Entity Framework will correctly think that the database and your model is up-to-date and that this was only achieved by running the migration step initial and this way you can keep all your data.

Of course for doing this to multiple databases you only need to do these steps once and for the other databases you just need to delete the current rows in the __MigrationHistory table and insert the new row for the Initial migration step.

Upvotes: 1

Related Questions