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.
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.
Below are simple steps to use migrations on both Windows and macOS using the .NET CLI (Command Line Interface).
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
To add a migration, run the following command. Replace `
dotnet ef migrations add
dotnet ef migrations add
This command generates a migration file in the `Migrations` folder, containing the changes to your data model.
To update the database with the new migration, run the following command:
dotnet ef database update
dotnet ef database update
The database schema will now match your data model.
To revert to a specific migration, use the following command and replace `
dotnet ef database update
dotnet ef database update
Let's assume you want to add a new column to the `Product` table.
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
}
dotnet ef migrations add AddDescriptionColumn
dotnet ef database update
The `Description` column will now be added to the `Product` table in the database.
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.