EF Core Operations

Manage Entity Framework Core migrations and database updates.

Operations

Operation Description
Ef.DbContextFrom
Create a reference to a DbContext in a project.
var db = Ef.DbContextFrom(DataProject);
var db = Ef.DbContextFrom(DataProject, "AppDbContext");
Ef.DatabaseUpdate
Apply pending EF Core migrations to the database.
Ef.DatabaseUpdate(db);
Ef.DatabaseUpdate(db, connectionString: "Server=...");
Ef.AddMigration
Create a new EF Core migration.
Ef.AddMigration(db, "InitialCreate");
Ef.AddMigration(db, "AddUsers", outputDir: "Migrations");
Ef.Script
Generate an idempotent SQL migration script.
Ef.Script(db, Root / "migration.sql");
Ef.Script(db, Root / "migration.sql", fromMigration: "Init");
Ef.RemoveMigration
Remove the last migration.
Ef.RemoveMigration(db);
Ef.RemoveMigration(db, force: true);

Setup

EF Core operations require the dotnet-ef tool. ANDO can install it automatically.

build.ando
// Define the EF tool (installs if needed)
var EfTool = Dotnet.Tool("dotnet-ef", "9.0.0");

Example

Run migrations and generate SQL scripts.

build.ando
// Define the DbContext reference
var DataProject = Project.From("./src/Data/Data.csproj");
var db = Ef.DbContextFrom(DataProject, "AppDbContext");

// Apply migrations to the database
Ef.DatabaseUpdate(db);

// Or generate an idempotent SQL script
Ef.Script(db, Root / "artifacts" / "migration.sql");