Skip to content

Instantly share code, notes, and snippets.

@Anduin2017
Created June 24, 2019 07:12
Show Gist options
  • Save Anduin2017/4c549eb4c0e15239e45cd8f55cb8b30a to your computer and use it in GitHub Desktop.
Save Anduin2017/4c549eb4c0e15239e45cd8f55cb8b30a to your computer and use it in GitHub Desktop.
Auto update database in ASP.NET Core
public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost, Action<TContext, IServiceProvider> seeder = null) where TContext : DbContext
{
using (var scope = webHost.Services.CreateScope())
{
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILogger<TContext>>();
var context = services.GetService<TContext>();
var configuration = services.GetService<IConfiguration>();
var env = services.GetService<IHostingEnvironment>();
var connectionString = configuration.GetConnectionString("DatabaseConnection");
try
{
logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");
logger.LogInformation($"Connection string is {connectionString}");
var retry = Policy.Handle<Exception>().WaitAndRetry(new[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15),
});
retry.Execute(() =>
{
// Migrate even in production level.
context.Database.Migrate();
if (env.IsDevelopment())
{
try
{
seeder?.Invoke(context, services);
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred while seeding the database used on context {typeof(TContext).Name}");
}
}
});
logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred while migrating the database used on context {typeof(TContext).Name}");
}
}
return webHost;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment