EF Core by Doug

Custom Migrations Operations

To create a Custom Migration in EF Core, follow these steps.

Create an empty migration using the command

dotnet ef migrations add "migration name"

Inside the Up(MigrationBuilder migrationBuilder) method in the generated migration file, add your custom SQL statements using migrationBuilder.Sql.

public partial class CustomMigration : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("CREATE TABLE CustomTable (Id int, Name varchar(50));");
        migrationBuilder.Sql("INSERT INTO CustomTable (Id, Name) VALUES (1, 'Example');");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("DROP TABLE CustomTable;");
    }
}

For more detailed information, refer to Custom Migrations Operations - EF Core | Microsoft Learn

Comments