Entity Framework Migrations

Entity Framework Migrations is a feature that helps manage database schema changes in a controlled way. Migrations allow you to update your database as your application evolves without losing existing data.


What Are Migrations?

Migrations track changes to your data model and apply these changes to the database schema. They make it easier to keep your database in sync with your application's code.


How to Use Migrations?

Below are simple steps to use migrations on both Windows and macOS using the .NET CLI (Command Line Interface).


Step-by-Step Example

Step 1: Install the Tools

Ensure you have the Entity Framework CLI tools installed. Run the following command in your terminal or command prompt:

dotnet tool install --global dotnet-ef

If already installed, update the tools:

dotnet tool update --global dotnet-ef

Step 2: Create a Migration

To add a migration, run the following command. Replace `` with a descriptive name for your migration.

  • Windows: Use Command Prompt or PowerShell.
    dotnet ef migrations add 
  • macOS: Use Terminal.
    dotnet ef migrations add 

This command generates a migration file in the `Migrations` folder, containing the changes to your data model.


Step 3: Apply the Migration to the Database

To update the database with the new migration, run the following command:

  • Windows:
    dotnet ef database update
  • macOS:
    dotnet ef database update

The database schema will now match your data model.


Step 4: Rollback a Migration (Optional)

To revert to a specific migration, use the following command and replace `` with the target migration:

  • Windows:
    dotnet ef database update 
  • macOS:
    dotnet ef database update 

Example: Adding a New Column

Let's assume you want to add a new column to the `Product` table.

  1. Step 1: Update the `Product` model.
    
    public class Product {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; } // New column
    }
                            
  2. Step 2: Add a migration:
    dotnet ef migrations add AddDescriptionColumn
  3. Step 3: Apply the migration:
    dotnet ef database update

The `Description` column will now be added to the `Product` table in the database.


Conclusion:

Entity Framework Migrations provide a simple and effective way to manage database schema changes. Whether you are on Windows or macOS, the steps are straightforward and consistent, making it easy to keep your application and database in sync.