public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// Ensure the database is created and apply migrations if it is empty
using (var scope = app.ApplicationServices.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<DbContext>();
// Retrieve the IRelationalDatabaseCreator service from the service provider
var databaseCreator = dbContext.Database
.GetService<IRelationalDatabaseCreator>();
// Check if the database exists, and create it if it doesn't
// Create the database If SQL server is local.Otherwise don't apply migration and database creation
if (!databaseCreator.Exists())
{
databaseCreator.Create();
// Check if the database has any tables
if (!databaseCreator.HasTables())
{
dbContext.Database.Migrate();
}// Apply all migrations
}
}
}
}
No comments:
Post a Comment