Migrations in Entity Framework Core

Migrations in Entity Framework Core

Entity Framework Core 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 window itself.

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

Next, add an entity class Client.cs inside the Models folder. The Client.cs is for referencing the details of the clients of the company.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EFMigration.Models
{
    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; }
    }
}

Now add the Database Context class called CompanyContext.cs inside the Models folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace EFMigration.Models
{
    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;");
            }
        }
    }
}

You are now all set to perform EF Core Migrations.

The migration commands need dotnet ef to be installed in your pc. If you do not have it then go to Tools ➤ NuGet Package Manager ➤ Package Manager Console and run the following command.

PM> dotnet tool install --global dotnet-ef

Worth Mentioning – If you already had dotnet ef installed then it should be updated to the latest version. Run the following update command to do this job.

PM> dotnet tool update --global dotnet-ef

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> dotnet ef migrations add Migration1

or

PM> add-migration 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: It is 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 has changed when creating the next migration.

Check the below given image of these files.

migration files

Now the migration is 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> dotnet ef database update 

or

PM> Update-Database
Note: If the database is already create before then the update migration command will only create the tables on that database.

Now check the SQL Server you will find a new database created, which has the Client table on it. A db table called _EFMigrationsHistory, which will store the name of all migrations, will also be created.

table created

Using the –context Keyword

If your project has more than 1 Database Context files then with the keyword called –context you can specify which DbContext file to target.

Suppose your project has 2 Database Context files which are – CompanyContext.cs & EmployeeContext.cs. Then you can specify which db context to be targeted like:

PM> dotnet ef migrations add Migration1 --context EmployeeContext
PM> dotnet ef database update --context EmployeeDbContext

In the above code I am targeting the EmployeeContext for migrations.

How to Revert Database to Previous State

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EFMigration.Models
{
    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> dotnet ef database update Migration1

Now check the Client table once again and you will see the Address column is 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> dotnet ef migrations remove

or

PM> remove-migration
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 the database use any of the following command.

PM> dotnet ef database drop

or

PM> Drop-Database

Generate SQL Script

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

PM> dotnet ef migrations script

or

PM> script-migration

The script command will generate a script for all the migrations by default. This generated db script can be executed to form a duplicate database if you have a requirement.

Download the source code:

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

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