Joydip Kanjilal
Contributor

How to work with EF Core migrations in ASP.NET Core

how-to
Mar 23, 20236 mins
C#Microsoft .NETSoftware Development

Take advantage of migrations in EF Core to manage database schema changes over time and keep them in sync with the data models of your ASP.NET Core applications.

birds in flight leader lead team syncronized
Credit: Getty Images

An object-database mapper for .NET Core, Entity Framework Core is the open-source, cross-platform counterpart of the Entity Framework ORM (object-relational mapper) for .NET. Among the notable features of EF Core is the ability to carry out migrations to update your database schemas and ensure they are kept in sync with the data models of your applications.

In this article, we will delve into the rudiments of using EF Core migrations in ASP.NET Core 7 applications. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio 2022

First off, let’s create an ASP.NET Core 7 project in Visual Studio 2022. Follow these steps:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, uncheck the check box that says “Use controllers…” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” set to “None” (default).
  9. Ensure that the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” are unchecked as we won’t be using these features here.
  10. Click Create.

We’ll use this ASP.NET Core 7 Web API project to work with EF Core migrations in the sections below.

What are EF Core migrations?

In software development, it’s common to make changes to the data model as requirements evolve. These changes could involve adding new tables, modifying existing tables, or deleting tables altogether. Without migrations, applying these changes to a database would be difficult and error-prone.

A migration is the process of managing changes to a database schema as they occur over time. Migrations help you ensure that the database schema and the domain model in your application are in sync.

You can take advantage of migrations to enhance or alter your database schema by adding, eliminating, or altering database elements like tables, indexes, columns, and associations. Using migrations, developers can precisely log changes to the database schema, implement those changes in a well-organized manner, and undo any changes or modifications if required.

Note that migrations are enabled in EF Core by default. You can work with migrations either from within Visual Studio via the Package Manager Console or by using a command-line tool to run the EF Core CLI commands.

Install the EF Core NuGet packages

Create a class library project in the same ASP.NET Core 7 Web API project we created above. We’ll use this class library project to implement EF Core migrations. Assuming the initial project was named EFMigrationsDemo, name the class library project EFMigrationsDemo.Data.

At this time, your Solution Explorer will look like Figure 1 below.

ef core migrations 01 IDG

Figure 1: The Solution Explorer window at the start of our project.

Now, install the following three NuGet packages in the EFMigrationsDemo.Data project.

Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools

Next, install the following NuGet package in the starter project, EFMigrationsDemo, to ensure that the migrations will work successfully.

Microsoft.EntityFrameworkCore.Design

Create a model class in ASP.NET Core

Create a new file named Author.cs in your EFMigrationsDemo.Data project and enter the following code.

using System.ComponentModel.DataAnnotations;
namespace EFMigrationsDemo.Data
{
    public partial class Author
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }
}

Create the data context in ASP.NET Core

Create a new .cs file named named EFMigrationsDemoDBContext.cs in the EFMigrationsDemo.Data project and enter the following code in there.

using Microsoft.EntityFrameworkCore;
namespace EFMigrationsDemo.Data
{
    public partial class EFMigrationsDemoDBContext : DbContext
    {
        public EFMigrationsDemoDBContext(DbContextOptions
        <EFMigrationsDemoDBContext> options)
            : base(options)
        {
        }
        public virtual DbSet<Author> Author { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Author>(entity => {
                entity.HasKey(k => k.Id);
            });
            OnModelCreatingPartial(modelBuilder);
        }
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

Create a migration using EF Core

To create a migration, you should use the Add-Migration command in the NuGet Package Manager. For example, to create a new migration called MyDemoMigration in the Package Manager Console, execute the following command.

Add-Migration MyDemoMigration

Alternatively, you can execute the following command in the dotnet CLI.

dotnet ef migrations add MyDemoMigration

This will build a new migration file in the Migrations folder of your project, including code that represents the modifications to your data model. You can examine the resulting code (see Figure 2) to verify that it represents your intended revisions and make any required adjustments.

ef core migrations 02 IDG

Figure 2: The auto-generated Migration file.

Apply the migration using EF Core

To apply a migration to the database, you must already have created the migration. Next, use the Update-Database command at the Package Manager Console to apply the changes to your database. The following code snippet illustrates how you can apply the newest migration to the database.

Update-Database

Alternatively, you can use the following dotnet CLI command.

dotnet ef database update

This will apply any outstanding database migrations, bringing the schema in sync with your data model.

Figure 3 shows the database and the tables created after this command is executed.

ef core migrations 03 IDG

Figure 3: The database and its objects after executing the Database-Update command.

Remove a migration using EF Core

If you need to undo the last migration, use the Remove-Migration command in the Package Manager Console or the dotnet ef migrations remove command in the terminal. For instance, you could execute the following command in the Package Manager Console to erase the most recently applied migration.

Remove-Migration

Or you could execute the following dotnet CLI command.

dotnet ef migrations remove

The Remove-Migration command is adept at removing the last-applied migration and updates the database schema accordingly to match the previous migration. In other words, the command will delete the most recent migration from the Migrations folder of the project and change the database schema to reflect the migration before it.

Revert a migration using EF Core

You might often need to revert changes made in your database to an earlier migration. To update the database to a previous state, you can use the following syntax.

update-database <migration name>

Hence, to revert changes made to the database to the migration named MyInitialMigration, you would use the following command.

Update-database MyInitialMigration

Alternatively, you could use the following dotnet CLI command.

dotnet ef database update MyInitialMigration

Migrations are a core component of EF Core that enables developers to handle database schema changes in an organized and efficient manner. By using migrations, you can apply changes to your database schema when needed, revert such changes when necessary, and monitor changes to the database schema over time.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author