ASP.NET Core - Automatic EF Core Migrations to SQL Database on Startup

Example code tested with ASP.NET Core 3.1

This is a super quick example of how to automatically migrate database changes from code in ASP.NET Core using Entity Framework Core from the Startup.cs file.


Register the EF Core DB Context as an ASP.NET Core Service

The Entity Framework Core DB Context is registered as a service with the ASP.NET Core Dependency Injection (DI) system from the ConfigureServices() method of the Startup.cs file.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
    services.AddDbContext<DataContext>(x => x.UseSqlite("Data Source=LocalDatabase.db"));


Use the EF Core DB Context Service to automatically migrate database changes

An instance of the EF Core DB Context service is injected as a parameter into the Configure() method of the Startup.cs file, the DB Context instance is then used to apply any pending migrations to the database by calling the Database.Migrate() method.

// 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)


Extra Info

The above code sample is taken from this tutorial, to jump directly to the complete Startup.cs file in the tutorial use this link.

While updating the tutorial from an EF Core InMemory database to SQLite I ran into some difficulties trying to automatically run database migrations from the Startup.cs. At first I was following a tutorial on the MS Docs website that called services.BuildServiceProvider().GetService<MyDatabaseContext>().Database.Migrate(); from within the ConfigureServices() method, but this resulted in the following warning in the console when I ran the application:

Startup.cs(39,13): warning ASP0000: Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created.
Consider alternatives such as dependency injecting services as parameters to 'Configure'.


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 ASP.NET Core Help?

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

Supported by