.NET 6.0 - Execute EF Database Migrations from Code on Startup
Tutorial built with .NET 6.0
Other versions available:
- .NET: .NET 5.0
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.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
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.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some .NET Help?
Search fiverr to find help quickly from experienced .NET developers.