(EF Core) What are Database Migrations

In this tutorial we shall learn an introduction to the database migrations. This feature is provided by entity framework core through its command line tools.
(Rev. 30-Sep-2022)

Categories | About |     |  

Parveen,

What is Migration?

First let me explain the basic concept of a migration.

  1. In a real world application, projects evolve and therefore modifications are always required. Over a period of time, model classes need additions and alterations.
  2. Modifications to the model classes need a corresponding modification to the database schema and its tables, and their relationships.
  3. 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.

Video Explanation

Please watch the following youtube video:

What are the types of Changes during Migration?

Following are examples -

  1. Addition/Removal/Renaming of a new table, relationship, column, or changes to the datatype of a column.
  2. 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.

  1. A command called Add-Migration is 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.
  2. 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.
  3. The C# file and the migrations table serve as a snapshot for the next migration.
  4. Optionally, Script-Migration command 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.
  5. Lastly, a command called Update-Database is 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.