Entity Framework Core (Ef)

Manage Entity Framework Core migrations and database updates.

Operations

Operation Description
Ef.DbContextFrom
Create a reference to a DbContext in a project.
Ef.DatabaseUpdate
Apply pending EF Core migrations to the database. Can accept a connection string or an OutputRef from a Bicep deployment.
Ef.Script
Generate an idempotent SQL migration script.

Operation Details

Ef.DbContextFrom source

Create a reference to a DbContext in a project.

var db = Ef.DbContextFrom(DataProject);
var db = Ef.DbContextFrom(DataProject, "AppDbContext");

Ef.DatabaseUpdate source

Apply pending EF Core migrations to the database. Can accept a connection string or an OutputRef from a Bicep deployment.

Ef.DatabaseUpdate(db);
Ef.DatabaseUpdate(db, connectionString: "Server=...");
Ef.DatabaseUpdate(db, deployment.Output("sqlConnectionString"));

Ef.Script source

Generate an idempotent SQL migration script.

Ef.Script(db, Root / "migration.sql");
Ef.Script(db, Root / "migration.sql", fromMigration: "Init");

Setup

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

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

Example

Run migrations and generate SQL scripts.

// Define the DbContext reference
var DataProject = Dotnet.Project("./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");

Operations Reference

Ef.DbContextFrom

Creates a reference to an EF Core DbContext for use in other operations.

ParameterDescription
projectProjectRef pointing to the project containing the DbContext.
contextNameName of the DbContext class (e.g., “AppDbContext”). If the project has only one DbContext, this can be omitted.

Ef.DatabaseUpdate

Applies all pending migrations to the database.

ParameterDescription
contextDbContext reference from Ef.DbContextFrom().
connectionStringOptional connection string. If not provided, uses the connection string from the DbContext’s configuration.

Ef.Script

Generates an idempotent SQL script for all migrations.

ParameterDescription
contextDbContext reference from Ef.DbContextFrom().
outputFilePath where the SQL script will be written.
fromMigrationOptional starting migration. Only generates SQL for migrations after this point.