.NET 6.0 – Execute EF Database Migrations from Code on Startup

Tutorial: .NET 6.0 – Execute EF Database Migrations from Code on Startup

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

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

More Error Tutorials >>

Vue 3+VeeValidate – Form Validation Example (Composition API)

Vue 3+VeeValidate – Required Checkbox Example (Composition API)

Vue 3+Pinia-JWT Authentication Tutorial & Example

Leave a Reply

Your email address will not be published.

error: Content is protected !!