Migrations in Entity Framework Core

Migrations in Entity Framework Core

Using Migrations you can keep the database synchronized with the domain (entity) classes. When developing a project the programmers keep on updating the entity classes. Therefore they need to run migrations to keep the database schema up to date. Migration commands can be execute in NuGet Package Manager Console or in dotnet Command Line Interface (CLI).

To begin understanding the different migration commands of the Entity Framework Core, create a new ASP.NET MVC Core 2.0 project and install Entity Framework Core into it.

Next Add an entity class Client.cs & context class CompanyContext.cs inside the Models folder.

public class Client
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Country { get; set; }

    public string TelephoneNo { get; set; }

    public string Email { get; set; }
}
public class CompanyContext : DbContext
{
    public DbSet<Client> Client { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }
}

The Client.cs is for referencing the client details of the company.

Add Migration Command

The Add Migration command will create Migration files that store data from your entity classes.

On your Tools > NuGet Package Manager > Package Manager Console execute any of the following 2 commands to create the migration.

PM> add-migration Migration1

Or DotNet CLI Command:

PM> dotnet ef migrations add Migration1
Migration1 is the name of my migration.

The migration command will create a folder named Migrations on the application root. This folder contains 3 files.

  • _.cs: Its the main migration file which includes migration operations named Up() and Down() methods. The Up() method is responsible for creating DB objects while the Down() method removes them.
  • _.Designer.cs: The migrations metadata file which contains some extra information.
  • ModelSnapshot.cs: A snapshot of your current model. This is used to determine what changed when creating the next migration.

migration files

Now with migration created you can create your database.

Update Migration Command

The Update Migration command will create the database based on the migration created by the Add migration command.

You can execute either of the 2 update migration command given below:

PM> Update-Database

CLI version:

PM> dotnet ef database update 
If the database is already create before then the update migration command will only create the tables on the database.

Now check the SQL Server you will find a new database created, which has Client table on it.

For the first migration, a table called __EFMigrationsHistory, which will store the name of all migrations, will also be created.

table created

How to revert database to previous state

On my entity class Client.cs I add a new string property for address.

public class Client
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Country { get; set; }

    public string TelephoneNo { get; set; }

    public string Email { get; set; }

    public string Address { get; set; }
}

To update the database Client table so that it contains this new Address field. I add a new migration and name it Migration2. Next I run the update command.

PM> dotnet ef migrations add Migration2
PM> dotnet ef database update

If you now check the client table on the database you will see the address field added to it.

address field added to client table

Suppose some situation arises and you need to revert the database to the previous state i.e. when the Client table does not have the Address field.

To do this, run the Update command for Migration1 (which is the previous migration).

PM> Update-database Migration1

Or DotNet CLI version:

PM> dotnet ef database update Migration1

Now check the Client table once again, you will see the Address field removed from it.

client table reverted to previous state

In this way you can revert the database to previous state.

Remove Migration Command

With the Remove Migration command you can remove the last migration if it is not applied to the database.

You can execute either of the 2 command given below:

PM> remove-migration

CLI version:

PM> dotnet ef migrations remove
If the migration has already been applied to the database then you will get the following error – “The migration has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.”

Drop Database

To drop database use any of the following command.

PM> Drop-Database

Or CLI version.

PM> dotnet ef database drop

Generate SQL Script

You can also generate SQL Script of the database. To do this, execute either of the following 2 commands.

PM> script-migration

Or CLI version:

PM> dotnet ef migrations script

The script command will generate a script for all the migrations by default. To specify a range of migrations use the -to and -from options.

This script can be executed to form a duplicate database if you have a requirement.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.