Published:

.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
builder.Services.AddDbContext<DataContext>();
...


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>();
    dataContext.Database.Migrate();
}

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some .NET Help?

Search fiverr to find help quickly from experienced .NET developers.



Supported by