Migrations in Entity Framework 6

Author - Webner
28.07.2020
|
0 Comments
||

Whenever a data model changes during development it gets out of sync with the current database in code first approach. The database initialization strategies that we used in our project result in loss of data whenever there are changes in model classes. The solution to this problem is migrations. By using migrations your changes are updated in the database without any loss of data. Migrations keep existing data and update new data in your database.

Types of Migration

  • Automated Migration
  • Code-based Migration

Using Automated Migrations

Automatic Migration allows you to not run add-migration command for your changes in the models, but you have to run the update-database command manually.
If Automatic Migration is enabled when you call update-database, if there are any changes that are pending in your models, an ‘automatic’ migration will be added and the database will be updated.
You can eliminate the need to run an update-database command every time by adding a Database. SetInitializer(…) in OnModelCreating() method in your context,

Commands to add Automated Migration in your project:

  1. Go to Tools => Nuget Package manager and then package manager console.
  2. Run the enable-migrations –EnableAutomaticMigration:$true command in console.
  3. migrations

  4. This command creates a class named configuration which is derived from DbMigrationConfiguration.

By following the above steps in the constructor of the Configuration class, AutomaticMigrationsEnabled is set to true.
public Configuration() {
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "ContextModel.MyContext";
}

Using Code-Based Migration

When using code-based migrations every time you need to run commands manually when you make changes in your model class. To use code-based migration, you have to execute the following commands in the Package Manager Console in Visual Studio:

  1. Enable-Migrations:- Enable-Migrations create a Configuration class in your project to enable migrations.
  2. Add-Migration:- Creates a new migration class with a specified name with the Up() and Down() methods.
  3. Update-Database:-This apply changes to the database schema.

Now, if you change the domain classes, execute Add-Migration with the name parameter to create a new migration file and then execute the Update-Database command to apply the changes to the database schema.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *