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.
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"));
...
}
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)
dataContext.Database.Migrate();
...
}
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'.
[/Users/jwatmore/Projects/aspnet-core-3-registration-login-api/WebApi.csproj]
#aspdotnet #dotnet #SQL #Database #database