Microsoft Learn

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

Step‑by‑Step Guide

  1. 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;");
}
  1. 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.

  1. 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

Further Reading