Press "Enter" to skip to content

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

Entity Framework Core, an object database mapper for .NET Core, is the open source, cross-platform counterpart of the Entity Framework ORM (Object Relational Mapper) for .NET. Notable features of EF Core include the ability to perform migrations to update your database schemas and ensure they stay in sync with your applications’ data models.

In this article, we’ll dive into the rudiments of using EF Core migrations in ASP.NET Core 7 applications. To use the code samples provided in this article, you must have Visual Studio 2022 installed on 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, let’s create an ASP.NET Core 7 project in Visual Studio 2022. Follow these steps:

  1. Start the Visual Studio 2022 IDE.
  2. Click “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 “Set up your new project” window, specify the name and location of the new project.
  6. Optionally, check the “Place solution and project in the same directory” checkbox, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown below, uncheck the checkbox that says “Use Controllers…” as we will be using minimal APIs in this example. Leave the “Authentication Type” set to “None” (default).
  9. Make sure the “Enable Open API Support”, “Configure for HTTPS”, and “Enable Docker” checkboxes are not checked, as we will not 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 is common to make changes to the data model as requirements evolve. These changes could involve adding new tables, modifying existing tables, or removing tables entirely. 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 domain model in your application are in sync.

You can take advantage of migrations to enhance or modify your database schema by adding, removing, or modifying database elements such as tables, indexes, columns, and associations. With migrations, developers can accurately record changes to the database schema, deploy those changes in a well-organized manner, and roll back any changes or modifications if necessary.

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

Install EF Core NuGet packages

Create a class library project in the same ASP.NET Core 7 Web API project that we created earlier. We will 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 point, your Solution Explorer will look like Figure 1 below.

ef 01 core migrations IDG

Figure 1: The Solution Explorer window at the beginning 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 your starter project, EFMigrationsDemo, to ensure that your migrations work correctly.

Microsoft.EntityFrameworkCore.Layout

Create a model class in ASP.NET Core

Create a new file called 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 EFMigrationsDemoDBContext.cs in the EFMigrationsDemo.Data project and enter the following code 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 with EF Core

To create a migration, you must use the Add-Migration command in the NuGet Package Manager. For example, to create a new migration named MyDemoMigration in the package manager console, run the following command.

Add-Migration MyDemoMigration

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

Also Read:  Regex: Processing patterns in text
dotnet ef migrations add MyDemoMigration

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

ef 02 core migrations IDG

Figure 2: The automatically generated migration file.

Apply migration using EF Core

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

Update-Database

Alternatively, you can use the following dotnet CLI command.

dotnet ef database update

This will apply any pending database migrations, synchronizing the schema with your data model.

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

ef 03 core migrations IDG

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

Delete a migration with 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 terminal. For example, you could run the following command in the Package Manager Console to clear the most recently applied migration.

Remove-Migration

Or you could run the following dotnet CLI command.

dotnet ef migrations remove

He Remove-Migration The 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 remove the most recent migration from the project’s Migrations folder and change the database schema to reflect the previous migration.

Revert a migration with EF Core

You may often need to revert changes made to your database to a previous migration. To upgrade the database to a previous state, you can use the following syntax.

update-database <migration name>

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

Update-database MyInitialMigration

Alternatively, you can use the following dotnet CLI command.

dotnet ef database update MyInitialMigration

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

Copyright © 2023 IDG Communications, Inc.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *