After creating migrations in Entity Framework Core, the next step is to apply those migrations to your database. This process updates the database schema to reflect the changes defined in your migrations. The .NET Command Line Interface (CLI) provides a simple command to apply migrations. This guide will walk you through the steps to apply migrations to the database using the CLI.

What are Migrations?

Migrations are a way to manage changes to your database schema over time. They allow you to create, modify, and delete database objects such as tables and columns in a structured manner. Each migration is represented by a class that contains methods to apply and revert the changes.

How to Apply Migrations

To apply migrations to your database using the CLI, follow these steps:

Step 1: Open Your Command Line Interface

Open your terminal (macOS/Linux) or command prompt (Windows).

Step 2: Navigate to Your Project Directory

Use the cd command to navigate to the directory of your ASP.NET Core project that contains the DbContext class and the migrations. For example:

cd /path/to/your/MyWebApp

Step 3: Run the dotnet ef database update Command

Use the following command to apply the migrations to your database:

dotnet ef database update

This command applies all pending migrations to the database, updating the schema to match the current model defined in your application.

Example

Suppose you have created several migrations and want to apply them to your database. You would execute the following command:

dotnet ef database update

After executing this command, you should see output indicating that the migrations are being applied. The output will show the migrations being executed and any changes being made to the database.

Applying a Specific Migration

If you want to apply a specific migration rather than all pending migrations, you can specify the migration name in the command:

dotnet ef database update MigrationName

Replace MigrationName with the name of the migration you want to apply. This command will apply the specified migration and any migrations that precede it.

Example of Applying a Specific Migration

If you want to apply a migration named AddProductDescription, you would run:

dotnet ef database update AddProductDescription

This command applies the AddProductDescription migration and any previous migrations that have not yet been applied.

Conclusion

Applying migrations to the database using the CLI is a straightforward process that helps you keep your database schema in sync with your application model. By following the steps outlined in this guide, you can easily apply all pending migrations or target specific migrations as needed. Understanding how to manage migrations is essential for any developer using Entity Framework Core in their ASP.NET Core applications.