How to perform database migrations using Entity Framework Core in ASP .NET 8?

 Database migrations in Entity Framework Core (EF Core) are a way to update the database schema in a controlled and incremental manner. They are particularly useful for evolving the database schema over time as your application evolves. Here’s a step-by-step guide on how to perform database migrations using EF Core in ASP.NET 8.

1. Setup and Configuration

Before you can perform migrations, you need to set up Entity Framework Core in your ASP.NET 8 application. Here’s how you can do that:

1.1. Install EF Core Packages

You need to install the Entity Framework Core packages. You can do this via NuGet Package Manager or the CLI.

Using NuGet Package Manager Console:

bash

Install-Package Microsoft.EntityFrameworkCore Install-Package Microsoft.EntityFrameworkCore.Design Install-Package Microsoft.EntityFrameworkCore.SqlServer # Or any other database provider

Using .NET CLI:

bash

dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or any other database provider

1.2. Configure DbContext

Define a DbContext class and configure it in Program.cs (or Startup.cs for older ASP.NET Core versions).

Example: MyDbContext.cs

csharp

using Microsoft.EntityFrameworkCore; public class MyDbContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Fluent API configurations (if any) go here } }

Example: Configure DbContext in Program.cs

csharp

var builder = WebApplication.CreateBuilder(args); // Configure DbContext with SQL Server (or another provider) builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); var app = builder.Build();

1.3. Add Connection String

Add the connection string to appsettings.json.

Example: appsettings.json

json

{ "ConnectionStrings": { "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" } }

2. Creating and Applying Migrations

Once EF Core is set up, you can create and apply migrations.

2.1. Add a Migration

A migration represents a set of changes to the database schema.

Using .NET CLI:

bash

dotnet ef migrations add InitialCreate

Using Package Manager Console:

bash

Add-Migration InitialCreate
  • InitialCreate: The name of the migration. You can choose any descriptive name.

This command generates a migration file in the Migrations folder. The file contains code to apply and revert the changes made to the database schema.

2.2. Apply the Migration

To apply the migration and update the database schema:

Using .NET CLI:

bash

dotnet ef database update

Using Package Manager Console:

bash

Update-Database

This command updates the database schema based on the migration files.

3. Managing Migrations

3.1. Viewing Pending Migrations

You can view the list of pending migrations that have not yet been applied to the database.

Using .NET CLI:

bash

dotnet ef migrations list

Using Package Manager Console:

bash

Get-Migrations

3.2. Removing the Last Migration

If you need to remove the last migration (e.g., if it was created by mistake), you can do so:

Using .NET CLI:

bash

dotnet ef migrations remove

Using Package Manager Console:

bash

Remove-Migration
  • This will remove the last migration file but will not affect the database.

4. Handling Data Changes

When you make changes to your models, such as adding a new property or changing a relationship, you need to create a new migration to apply these changes to the database.

  1. Update Models: Modify your entity classes and/or DbContext.

  2. Create a Migration: Add a new migration to capture the changes.

    bash

    dotnet ef migrations add AddedNewProperty
  3. Apply the Migration: Update the database with the new migration.

    bash

    dotnet ef database update

5. Customizing Migrations

Sometimes, you might need to customize the migration code. You can manually edit the migration files generated in the Migrations folder.

Example: Adding a custom migration script

csharp

public partial class AddedNewProperty : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "NewProperty", table: "Products", type: "nvarchar(max)", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "NewProperty", table: "Products"); } }
  • Up Method: Contains the code to apply changes to the database schema.
  • Down Method: Contains the code to revert changes if the migration is rolled back.

6. Seeding Data

You can seed initial data into your database using migrations.

Example: Seeding Data in OnModelCreating

csharp

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>().HasData( new Product { Id = 1, Name = "Sample Product", Price = 19.99M } ); }

To apply seeded data, create a migration after adding the seeding code and apply it.

7. Migrating to a New Database

If you need to initialize a new database with the current schema and data, use:

Using .NET CLI:

bash

dotnet ef database update

This will apply all migrations to the new database.

Summary

  1. Setup EF Core: Install necessary packages and configure DbContext.
  2. Create Migrations: Use dotnet ef migrations add or Add-Migration to create migration files.
  3. Apply Migrations: Use dotnet ef database update or Update-Database to update the database.
  4. Manage Migrations: View, remove, and customize migrations as needed.
  5. Handle Data Changes: Create new migrations for model changes and apply them.
  6. Seed Data: Initialize the database with default data using seeding.

By following these steps, you can effectively manage your database schema changes and keep your database in sync with your application’s data model.

Post a Comment