Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First Database Initializer and Migrations Confusion

I am on Entity Framework 6.0. This is a development issue, not Production.

I think I have a conflicting strategy in place. Currently I have a DropCreateDatabaseIfModelChanges database initializer set and have migrations enabled with a seed method in Configuration.cs. On adding a migration and running update-database, it seems like a lucky dip as to when the database is dropped and recreated and when the seed method runs. The fact is, it's a total lottery as to when either happens, and I have to pull all sorts of tricks to get the thing to work. Can someone tell me if it is conflicting to have both a database initialiser and migrations enabled. Thanks

like image 957
ShaunK Avatar asked Jul 05 '16 04:07

ShaunK


People also ask

Which of the following are database initialization strategies in EF code First?

DropCreateDatabaseAlways: This strategy of code first approach creates the database every time you run the application. If the database already exists and there is no modification done in the model, it will drop the database and create a new one.

How do you create a migration in code first approach?

Step 1 − Before running the application you need to enable migration. Step 2 − Open Package Manager Console from Tools → NuGet Package Manger → Package Manger Console. Step 3 − Migration is already enabled, now add migration in your application by executing the following command.

What is the purpose of code first migrations?

Code First Migrations allow you to create a new database or to update existing database based on your model classes by using Package Manager Console exist within Visual Studio 2013 or Visual Studio 2012.


1 Answers

That is not a proper combination. There is a MigrateDatabaseToLatestVersion Initializer for use with migrations.

During early development, you may want to use a DropCreateDatabaseIfModelChanges initializer (or CreateDatabaseIfNotExists). There is a special Seed() method for initializers that only runs when the database is created.

Once you reach a point where what's in the database is a pain to reseed you can switch to migrations. Change your initializer and enable migrations. Be sure to add an initial baseline migration (add-migration Initial -IgnoreChanges) so you will only get the changes after that point. You can now add migration Seeding that runs every time you update-database as opposed to the initializer Seed that only runs if the database is created.

If you need to recreate the database, you can generate an idempotent script that will create the database and apply all migrations.

like image 178
Steve Greene Avatar answered Sep 19 '22 13:09

Steve Greene