ASP.NET Core 8 Web API -

Migrations

Entity Framework Core (EF Core) migrations are a way to manage database schema changes over time. They provide a way to create, update, and rollback database schemas as your application evolves. This guide covers everything you need to know about using migrations in ASP.NET Core 8 Web API, including setup, commands, and best practices.


1. Introduction to Migrations

Migrations in EF Core are a way to incrementally evolve your database schema over time. They help you keep track of changes to your models and propagate those changes to your database schema. Migrations can be used to create tables, add columns, remove columns, and more.


2. Setting Up EF Core Migrations

2.1 Install EF Core Tools First, ensure you have the EF Core tools installed. You can install them using the .NET CLI:
        
            
dotnet tool install --global dotnet-ef

        
    

Next, add the EF Core packages to your project:
        
            
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

        
    


2.2 Configure DbContext Create a DbContext class that represents a session with the database. It includes DbSet properties for each entity.
        
            
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

    public DbSet<Product> Products { get; set; }
}

        
    


2.3 Register DbContext in Dependency Injection Register the DbContext in the DI container in Program.cs.
        
            
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); //ms sql server 

var app = builder.Build();

app.MapControllers();
app.Run();

        
    


Add the connection string to appsettings.json.
        
            
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

        
    

3. Creating Migrations

3.1 Add Initial Migration Create the initial migration to create the database schema based on your models.
        
            
dotnet ef migrations add InitialCreate

        
    

This command generates migration files in the Migrations folder, which include the instructions for creating the database schema.



3.2 Apply the Migration Apply the migration to create the database.
        
            
dotnet ef database update

        
    

This command applies all pending migrations to the database, creating or updating the database schema as needed.


4. Updating the Database Schema

As your application evolves, you'll need to update your database schema. EF Core migrations make this easy.

4.1 Add a New Property to a Model Modify your model by adding a new property.
        
            
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; } // New property
}

        
    


4.2 Create a New Migration Create a new migration to capture the changes.
        
            
dotnet ef migrations add AddDescriptionToProduct

        
    


4.3 Apply the New Migration Apply the migration to update the database schema.
        
            
dotnet ef database update

        
    

5. Rolling Back Migrations

If you need to revert changes, you can rollback migrations.

5.1 List Migrations List all migrations applied to the database.
        
            
dotnet ef migrations list

        
    


5.2 Revert to a Previous Migration Revert to a specific migration by specifying its name.
        
            
dotnet ef database update InitialCreate

        
    

This command reverts the database schema to the state it was in after the InitialCreate migration.


6. Customizing Migrations

You can customize migrations by editing the generated migration files.
        
            
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<string>(
        name: "Description",
        table: "Products",
        nullable: true);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "Description",
        table: "Products");
}

        
    

7. Using Seed Data

You can use migrations to seed initial data into the database.

7.1 Add Seed Data in the DbContext
        
            
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Product>().HasData(
        new Product { Id = 1, Name = "Product1", Price = 10.0m, Description = "Description1" },
        new Product { Id = 2, Name = "Product2", Price = 20.0m, Description = "Description2" }
    );
}

        
    


7.2 Create and Apply a Migration Create and apply a migration to add the seed data.
        
            
dotnet ef migrations add SeedInitialData
dotnet ef database update

        
    

8. Advanced Migrations

8.1 Renaming Columns To rename a column, use the RenameColumn method in the migration file.
        
            
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.RenameColumn(
        name: "OldName",
        table: "TableName",
        newName: "NewName");
}

        
    


8.2 Dropping Tables To drop a table, use the DropTable method in the migration file.
        
            
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropTable(
        name: "TableName");
}

        
    

9. Best Practices


10. Comprehensive Example

Here is a comprehensive example that demonstrates creating and applying migrations, updating the schema, seeding data, and rolling back migrations.

Step-by-Step Example: 10.1 Create Initial Migration
        
            
dotnet ef migrations add InitialCreate
dotnet ef database update

        
    


10.2 Add a New Property Modify the Product model to include a Description property.
        
            
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; } // New property
}

        
    


10.3 Create and Apply a New Migration
        
            
dotnet ef migrations add AddDescriptionToProduct
dotnet ef database update

        
    


10.4 Seed Initial Data Add seed data to the OnModelCreating method.
        
            
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Product>().HasData(
        new Product { Id = 1, Name = "Product1", Price = 10.0m, Description = "Description1" },
        new Product { Id = 2, Name = "Product2", Price = 20.0m, Description = "Description2" }
    );
}

        
    


10.5 Create and Apply Seed Data Migration
        
            
dotnet ef migrations add SeedInitialData
dotnet ef database update

        
    


10.6 Roll Back to a Previous Migration Revert the database to the state after the InitialCreate migration.
        
            
dotnet ef database update InitialCreate

        
    

11. Conclusion

Entity Framework Core migrations are a powerful tool for managing database schema changes in ASP.NET Core 8 Web API. By understanding how to create, apply, customize, and rollback migrations, you can effectively manage your database schema throughout the lifecycle of your application. This comprehensive guide provides a solid foundation for mastering EF Core migrations in ASP.NET Core 8 Web API, enabling you to build robust and maintainable applications.