ASP - Core Migrate EF Core SQL DB on Startup
A note from documentation on the call to db.Database.EnsureCreated()
:
Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.
You may just want to call db.Database.Migrate()
.
Comment taken from source found above declaration here.
You can use
db.Database.EnsureCreated();
to get your db up to date with your current model. If you want to enable migrations (If subsequent migrations are suspected), then use
db.Database.Migrate();
and put your subsequent migrations over time.
Use below code to run migration at
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<YourContext`enter code here`>();
context.Database.Migrate();
}
}
This works for me in ASP.NET Core 3.1, simply injecting the db context as a parameter to the existing Configure
method after registering it in the ConfigureServices
method.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlite("Data Source=LocalDatabase.db"));
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
dataContext.Database.Migrate();
...
}
More details and links to full code samples available at https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup