How to properly start using EF Migrations in an existing database

How to properly start using EF Migrations in an existing database

Migrations are a great way to keep for databases up-to-date with your code changes. When you decide to start using migrations when you app is running for a while and you have an existing database structure.

There is an easy way to trick Entity Framework to start applying migrations from a certain point in time. To achieve this, do the following:

  • Delete all existing files from the migrations (if any)
  • Clear any contents from the __EFMigrationsHistory table

Now, create a baseline with your existing tables

Add-Migration BaseLine -Project <APPNAME> -Context ApplicationDbContext

When this completes, a new migration file is created. Now generate a SQL file for this migrations. Do not apply this SQL script to the database.

Script-Migration -Idempotent -Project OpenLine.Automation.Web.Api -Context ApplicationDbContext

Look for the MigrationId at the top of the create sql file. The migration looks something like this: 20250414113559_BaseLine.

IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
    );
END;
GO

BEGIN TRANSACTION;
IF NOT EXISTS (
    SELECT * FROM [__EFMigrationsHistory]
    WHERE [MigrationId] = N'20250414113559_BaseLine'
)

Now, create a migration record manually with the following command:

INSERT INTO __EFMigrationsHistory (MigrationId, ProductVersion)
VALUES ('20250414113559_BaseLine', '9.0.0'); -- Adjust ProductVersion to your EF Core version

Now you have a new start point from which you can start using migrations without disturbing your existing structure.

Leave a Reply

Your email address will not be published. Required fields are marked *