What is Migration?
First let me explain the basic concept of a migration.
- In a real world application, projects evolve and therefore modifications are always required. Over a period of time, model classes need additions and alterations.
- Modifications to the model classes need a corresponding modification to the database schema and its tables, and their relationships.
- Don't forget that a running database contains critical, and linked data accumulated over months. A really reckless change on the C# side could lead to database corruption, could lead to data inconsistencies. Hence, a systematic process of data migration is required.
So we can say that migration is making incremental alterations to a database schema, while ensuring that the data of the previous version moves to the new version.
Please watch the following youtube video:
What are the types of Changes during Migration?
Following are examples -
- Addition/Removal/Renaming of a new table, relationship, column, or changes to the datatype of a column.
- Rollback of a previous migration or migrations.
Steps for Migration?
Migration is done with the help of EF Core Command line Migration tools.
Migration tools can be easily added to Visual studio. We shall practically demonstrate it later.
- A command called
Add-Migrationis used to add a migration by a readable name. The command line tools generate a C# source file on the basis of a snapshot of the old model and the new changes. The C# file is placed in a folder called "Migrations". This folder can be examined in the solution explorer.
- This C# file is serially numbered. This file contains auto-generated code for making changes to the database, and also for making an entry into a history table in your database.
- The C# file and the migrations table serve as a snapshot for the next migration.
Script-Migrationcommand can be used to generate a sequential SQL script of all the migrations from a blank database. This script can always be fine-tuned. This is a recommended step.
- Lastly, a command called
Update-Databaseis used to execute the changes on the database.
This Blog Post/Article "(EF Core) What are Database Migrations" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.