First, We need to enable database migrate by mentioning dbContext.Database.Migrate(); in Program.cs (in .NET 6).
Let’s add new property (database column) to required model class. Here we are adding new column BookDesc to Boooks table by adding BookDesc property to Book class as below.
publicclassBook
{
publicint BookId { get; set; }
publicstring Title { get; set; }
publicstring BookDesc { get; set; }
}
Now run Add-Migration command to create the Migration script by going to Visual Studio Tools => NuGet Package Manager => Package Manager Console and run below command.
Add-Migration AddColumnToBooksTableMigration
Please select Default project as EntityFramework project.
You can check the migration script in the Migrations folder and it looks like the below.
using Microsoft.EntityFrameworkCore.Migrations;
#nullabledisable
namespace EntityFrameworkCoreExample.Data.Migrations
{
publicpartialclassAddColumnToBooksTableMigration : Migration
{
protectedoverridevoid Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BookDesc",
table: "Books",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
protectedoverridevoid Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BookDesc",
table: "Books");
}
}
}
Run the application, and migrations scripts automatically as we are executing the dbContext.Database.Migrate() command and it adds the column BookDesc to the database table Books.