In the Code First approach, schema changes are made in C# and applied through migrations. Prerequisites - Packages: Microsoft.EntityFrameworkCore.SqlServer (or your provider) and Microsoft.EntityFrameworkCore.Design. - Tool: dotnet tool install --global dotnet-ef (or use the Package Manager Console in Visual Studio). Part 1 — Add a new table Step 1: Create the entity. public class Department { public int Id { get; set; } public string Name { get; set; } = ""; } Step 2: Add a DbSet to the DbContext (and optional configuration). public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options) { public DbSet<Department> Departments => Set<Department>(); protected override void OnModelCreating(ModelBuilder b) => b.Entity<Department>().Property(d => d.Name).HasMaxLength(100).IsRequired(); } Step 3: Create the migration. dotnet ef migrations add AddDepartmentsTable (Package Manager Console: Add-Migration AddDepartmentsTable) This generates a migration class with Up() (CreateTable) and Down() (DropTable) methods and updates the model snapshot. Review the generated code. Step 4: Apply it. dotnet ef database update (Package Manager Console: Update-Database) Part 2 — Add a single column Step 1: Add the property. public class Department { public int Id { get; set; } public string Name { get; set; } = ""; public string? Location { get; set; } // new column (nullable) } Step 2: Create the migration. dotnet ef migrations add AddLocationToDepartments The Up() method contains: migrationBuilder.AddColumn<string>(name: "Location", table: "Departments", type: "nvarchar(max)", nullable: true); Step 3: Apply it. dotnet ef database update Notes for production - If the new column is required (non-nullable), provide a default value (defaultValue in the migration or HasDefaultValue) so existing rows are valid. - Generate a reviewed SQL script for production instead of running update from a developer machine: dotnet ef migrations script --idempotent -o migrate.sql or build a migration bundle: dotnet ef migrations bundle. - To undo a migration that has not been applied: dotnet ef migrations remove. To revert the database: dotnet ef database update PreviousMigrationName. - Keep migrations in source control and never edit migrations that are already applied in shared environments.
Ravindra Wadile · · 0 likes