EF Core migrations track database schema changes alongside your code. Here’s how to use them effectively.
Basic Commands
# Create migration
dotnet ef migrations add AddUserTable
# Apply migrations
dotnet ef database update
# Revert to specific migration
dotnet ef database update PreviousMigrationName
# Generate SQL script
dotnet ef migrations scriptMigration File
public partial class AddUserTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Email = table.Column<string>(maxLength: 256)
},
constraints: table => table.PrimaryKey("PK_Users", x => x.Id));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("Users");
}
}Best Practices
- Always review generated migrations
- Test Down() methods
- Use SQL scripts for production
- Consider data migrations separately
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.