.NET 5.0 - Automatic Entity Framework Migrations to SQL Database on Startup
Example code tested with .NET 5.0
Other versions available:
- .NET: .NET 6.0
This is a super quick example of how to automatically migrate database changes from code in .NET 5.0 using Entity Framework in the Startup.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 ConfigureServices()
method of the Startup.cs
file by calling services.AddDbContext<TContext>()
.
This code snippet registers the EF context DataContext
as a .NET service.
// add services to the DI container
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>();
...
}
Execute Migrations Automatically on Startup with Entity Framework Context
After the EF context is registered as a .NET service, it can be added as a parameter to the Configure()
method of the Startup.cs
file and will be automatically injected by the .NET DI system. The injected context can then be used to automatically execute database migrations on app startup.
This example Configure()
method has the EF context DataContext
added as a parameter, migrations are executed on app startup by calling dataContext.Database.Migrate();
.
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
// migrate any database changes on startup (includes initial db creation)
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.