skip to content

In EF Core 10, how does Database.EnsureCreated differ from Database.Migrate, and why must one database never use both?

level: middleimportance: must knowfreq 55%

answer

  1. creates from the current model, once
  2. returns bool, never alters existing tables
  3. no __EFMigrationsHistory rows
  4. Migrate then tries to create tables again
  5. EnsureDeleted for disposable test databases

basics

~20 s

EnsureCreated builds the database and tables from the current model only when they are missing, keeps no migration history and never alters them later. Migrate applies and records migrations. Mixing them makes Migrate recreate existing tables and fail.

solid answer

~40 s

`EnsureCreated()` creates the database and every table straight from the current model when the database is missing or has no tables, inserts `HasData` rows, and returns `true`; otherwise it does nothing and returns `false`. It writes no rows to `__EFMigrationsHistory` and never alters an existing schema, so model changes after the first run are ignored. `Migrate()` applies migrations: it creates the database if needed, creates the history table, and applies each unapplied migration in order. Call `EnsureCreated` first on a database you also migrate and the tables exist with no history, so `Migrate` runs the initial migration and fails on tables that already exist. Use `EnsureCreated` with `EnsureDeleted` for prototypes and disposable test databases, and migrations for anything that must evolve.

code

csharp · 7 lines
csharp
// Disposable test database: rebuild from the model on every run
await using var db = new PayrollDbContext(options);
await db.Database.EnsureDeletedAsync();
var created = await db.Database.EnsureCreatedAsync(); // true: database and tables created

// Real database: apply migrations instead, never both
// await db.Database.MigrateAsync();

go deeper

for a junior

Know that EnsureCreated builds a schema once from the model while Migrate applies migrations, and that a real database uses only migrations.

for a middle

Explain what EnsureCreated checks, what it returns, why it leaves no history, and the exact failure when Migrate runs after it.

for a senior

Choose per environment: disposable test databases versus migration-tested ones, and know how to adopt migrations on a database EnsureCreated produced without losing data.

for a principal

Set the rule that every persistent database is migration-managed from day one, and decide when tests may trade fidelity for the speed of rebuilding from the model.

## Two ways to get a schema EF Core can put a schema into a database in two unrelated ways, both reached through `context.Database` (a `DatabaseFacade`): - **`EnsureCreated` / `EnsureCreatedAsync`**: build the whole schema from the **current model** in one go; - **`Migrate` / `MigrateAsync`**: replay the **migrations** in the migrations assembly, one step at a time, keeping a history. They look interchangeable on an empty database and behave completely differently on the second run. ## EnsureCreated For a payroll service's `PayrollDbContext`: 1. If the database does not exist, it creates it and all tables, keys and indexes from the model. 2. If the database exists but has no tables, it creates the tables. 3. Otherwise it does **nothing**. 4. It inserts `HasData` rows when it creates tables, and runs the `UseSeeding` delegate in every case. 5. It returns `true` if it created anything and `false` otherwise. What it never does: - write rows to `__EFMigrationsHistory`; - add the column you added to the model yesterday to a database it created last week; - use your migrations, including any hand-written `migrationBuilder.Sql` in them. `EnsureDeleted` is its companion: it drops the database, which makes `EnsureDeleted` plus `EnsureCreated` a quick reset for a throwaway test database. ## Migrate `Migrate` (and `MigrateAsync`) applies migrations: it creates the database if needed, creates the history table, takes EF Core's migration lock, applies each migration not yet recorded, inserts a history row per migration and then runs the seeding delegate. Every later model change reaches the database as a new migration. ## Why mixing them fails | Order on one database | Result | |---|---| | `EnsureCreated`, then `Migrate` | tables exist but the history table is empty; `Migrate` runs the initial migration, whose `CreateTable` fails because the table already exists | | `Migrate`, then `EnsureCreated` | the database has tables, so `EnsureCreated` returns `false` and does nothing; harmless but pointless | | `EnsureCreated` only, model changes later | the database keeps the old schema; queries hit missing columns | The EF Core docs say it directly: don't call `EnsureCreatedAsync()` before `MigrateAsync()`. ## Choosing | Situation | Use | |---|---| | A prototype or a demo whose database can be thrown away | `EnsureCreated` | | A disposable test database recreated per run | `EnsureDeleted` then `EnsureCreated` | | A test that must prove the migrations themselves work | `Migrate` on an empty database | | A non-relational provider such as Cosmos DB, or the in-memory provider | `EnsureCreated` (migrations are relational only) | | Any database whose data must survive schema changes | migrations, applied by `Migrate`, `database update`, a bundle or a script | ## Moving from EnsureCreated to migrations A database created by `EnsureCreated` has no history table at all. To adopt migrations, add an initial migration that matches the existing schema, then create `__EFMigrationsHistory` and insert that migration's id and EF Core version, so it counts as applied without running; `dotnet ef migrations script` for the initial migration prints both statements. Later migrations then apply normally. Dropping and recreating is simpler when the data is disposable. ## Interview traps - `EnsureCreated` is not a cheaper `Migrate`; it ignores migrations entirely. - `EnsureCreated` returning `false` does not mean the schema matches the model; it means the database already had tables. - Removing `EnsureCreated` from startup after go-live does not convert the database; it still has no history. ## What tests built on EnsureCreated miss A test suite that rebuilds its database with `EnsureCreated` exercises the **model**, not the **migrations**. That is fast and usually enough for query tests, but: - a migration with a wrong `Down`, a broken `migrationBuilder.Sql` statement or a rename scaffolded as a drop and an add passes every such test; - custom objects created only in migrations, such as views, functions or triggers, do not exist in the test database at all; - `HasData` rows are present, but anything a migration inserts with hand-written SQL is not. Keeping at least one test path that applies the real migrations with `Migrate` on an empty database catches these before release.

  • Your app called EnsureCreated in production for months; how do you start using migrations without losing data?
    Add an initial migration that matches the current schema, then create `__EFMigrationsHistory` and insert that migration's id and EF Core version, both statements printed by `dotnet ef migrations script` for it, so it counts as applied without running. From then on, add migrations normally. Check first that the initial migration really matches the live schema.
  • Why can't a Cosmos DB context use Migrate?
    Migrations are a relational feature: `Migrate` and `MigrateAsync` are extension methods for relational providers and rely on a history table and schema operations. A non-relational provider such as Cosmos DB uses `EnsureCreated` to create its database and containers instead.

  • EnsureCreated adds new columns to an existing database when the model changes.
  • Calling EnsureCreated before Migrate is a safe way to guarantee the database exists.
  • EnsureCreated records an initial migration in __EFMigrationsHistory.
  • EnsureCreated returning false means the schema matches the model.
  • Migrate needs EnsureCreated first because it cannot create a database.