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.
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.
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
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();
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
dotnet ef migrations add InitialCreate
This command generates migration files in the Migrations folder, which include the instructions for creating the database schema.
dotnet ef database update
This command applies all pending migrations to the database, creating or updating the database schema as needed.
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
}
dotnet ef migrations add AddDescriptionToProduct
dotnet ef database update
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
dotnet ef database update InitialCreate
This command reverts the database schema to the state it was in after the InitialCreate migration.
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");
}
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" }
);
}
dotnet ef migrations add SeedInitialData
dotnet ef database update
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "OldName",
table: "TableName",
newName: "NewName");
}
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TableName");
}
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
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
}
dotnet ef migrations add AddDescriptionToProduct
dotnet ef database update
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" }
);
}
dotnet ef migrations add SeedInitialData
dotnet ef database update
dotnet ef database update InitialCreate
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.