Entity Framework 4.3 includes a new Code First Migrations feature that allows you to evolve the database schema incrementally as your model changes over time. This is a big improvement for most developers over the database initialize options from the 4.1 and 4.2 releases that required you to manually update the database or drop and recreate it when your model changed.
There are two kinds of Migration:
Automated Migration was first introduced in Entity Framework 4.3. You don't need to process database migration manually in the code file in automated Migration. For example, you will also need to change your domain classes for each change. But with automated Migration, you have to run a command in Package Manager Console to get this done.
Let's take a look at the following step-by-step process of automated Migration.
When you use Code First approach, you don't have a database for your application.
Before running the application, you need to enable automated Migration.
Step 1 − Open Package Manager Console from Tools → NuGet → Package Manager Console.
Step 2 − To enable automated Migration, run the following command in the Package Manager Console.
Step 3 − Once the command runs successfully, it creates an internal sealed Configuration class in the Migration folder of your project.
Step 4 − Set the database initializer in the context class with the new DB initialization strategy MigrateDatabaseToLatestVersion.
Step 5 − You have set up automated Migration. When you execute your application, it will automatically take care of Migration when you change the model.
Step 6 − As you can see, one system table __MigrationHistory, is also created in your database with other tables. In __MigrationHistory, automated Migration maintains the history of database changes.
Step 7 − When you add another entity class as your domain class and execute your application, it will create the table in your database.
Step 8 − Don’t forget to add the DBSet
Step 9 − Run your application again, and you will see that the StudentsLogIn table is added to your database.
Step 10 − To handle the property migration, you need to set AutomaticMigrationDataLossAllowed = true in the configuration class constructor.
When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database when you change the data model. Code-based Migration is useful when you want more control over the Migration.
|