Setting a Baseline for Existing Databases
When adopting EF Core in an existing project, you often have a database that already contains tables, constraints, and data. Creating migrations from scratch would try to recreate everything, leading to errors. The dotnet ef migrations add command supports a baseline approach that tells EF Core to consider the current schema as the starting point.
Prerequisites
- .NET 6 SDK or later
- EF Core 6.x or later installed (
dotnet add package Microsoft.EntityFrameworkCore) - Existing database connection string
Step‑by‑Step Guide
- Configure your
DbContext
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server=.;Database=ShopDb;Trusted_Connection=True;");
}
- Scaffold an initial migration with
--ignore-changes
dotnet ef migrations add InitialBaseline --ignore-changes
The --ignore-changes flag tells EF Core to generate an empty migration – it records the model snapshot but produces no Up/Down operations.
- Apply the baseline migration
dotnet ef database update
This marks the existing database as being at version InitialBaseline. Future migrations will be generated based on changes you make to the model.
Adding Your First Real Migration
Now modify the model, for example add a new column to Product:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
// New property
public int Stock { get; set; } // ← added
}
Generate the migration:
dotnet ef migrations add AddStockToProduct
Inspect the generated migration (it will contain an ALTER TABLE statement). Then apply it:
dotnet ef database update
Tips & Common Pitfalls
- Always run
dotnet ef migrations add --ignore-changeson a clean slate before any real migrations. - If you need to re‑baseline (e.g., after a major refactor), delete the existing migrations folder, create a new baseline, and re‑apply.
- Commit the
ModelSnapshotfile; it represents the last applied migration.