Published: June 08 2021

.NET 5.0 - Automatic Entity Framework Migrations to SQL Database on Startup

Example code tested with .NET 5.0

Other versions available:

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();

    ...
}

 


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!


Comments


Supported by