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. 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: Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. 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). 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. 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. 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. 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. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos