Published: February 01 2022

.NET 6.0 - Execute EF Database Migrations from Code on Startup

Tutorial built with .NET 6.0

Other versions available:

This is a super quick example of how to automatically migrate database changes on startup from code in .NET 6.0 using Entity Framework in the Program.cs file.

Register the Entity Framework DB Context as a .NET Service

First register your EF Context with the .NET Dependency Injection (DI) system in the Program.cs file by calling builder.Services.AddDbContext<TContext>().

This code snippet registers the EF context DataContext as a .NET service.

var builder = WebApplication.CreateBuilder(args);

// add services to DI container

Execute DB Migrations Automatically on Startup with .NET Entity Framework

After the EF context is registered as a .NET service, it can be manually retrieved from the DI system by creating a scope and calling scope.ServiceProvider.GetRequiredService<TService>() like below.

Migrations are executed by calling dataContext.Database.Migrate();.

// migrate any database changes on startup (includes initial db creation)
using (var scope = app.Services.CreateScope())
    var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();


Need Some .NET Help?

Search fiverr for freelance .NET developers.

Follow me for updates

On Twitter or RSS.

When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Supported by