2017-09-13 14:53:06 +02:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
2017-11-02 15:03:32 +01:00
|
|
|
|
using Polly;
|
|
|
|
|
using Polly.Retry;
|
2017-09-13 14:53:06 +02:00
|
|
|
|
using System;
|
2017-11-02 15:03:32 +01:00
|
|
|
|
using System.Data.SqlClient;
|
2017-09-13 14:53:06 +02:00
|
|
|
|
|
|
|
|
|
namespace Microsoft.AspNetCore.Hosting
|
|
|
|
|
{
|
|
|
|
|
public static class IWebHostExtensions
|
|
|
|
|
{
|
|
|
|
|
public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost, Action<TContext,IServiceProvider> seeder) where TContext : DbContext
|
|
|
|
|
{
|
|
|
|
|
using (var scope = webHost.Services.CreateScope())
|
|
|
|
|
{
|
|
|
|
|
var services = scope.ServiceProvider;
|
|
|
|
|
|
|
|
|
|
var logger = services.GetRequiredService<ILogger<TContext>>();
|
|
|
|
|
|
|
|
|
|
var context = services.GetService<TContext>();
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");
|
|
|
|
|
|
2017-11-02 15:03:32 +01:00
|
|
|
|
var retry = Policy.Handle<SqlException>()
|
|
|
|
|
.WaitAndRetry(new TimeSpan[]
|
|
|
|
|
{
|
2018-05-22 15:33:21 +02:00
|
|
|
|
TimeSpan.FromSeconds(3),
|
2017-11-02 15:03:32 +01:00
|
|
|
|
TimeSpan.FromSeconds(5),
|
2018-05-22 15:33:21 +02:00
|
|
|
|
TimeSpan.FromSeconds(8),
|
2017-11-02 15:03:32 +01:00
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
retry.Execute(() =>
|
|
|
|
|
{
|
|
|
|
|
//if the sql server container is not created on run docker compose this
|
|
|
|
|
//migration can't fail for network related exception. The retry options for DbContext only
|
|
|
|
|
//apply to transient exceptions.
|
|
|
|
|
|
|
|
|
|
context.Database
|
2017-09-13 14:53:06 +02:00
|
|
|
|
.Migrate();
|
|
|
|
|
|
2017-11-02 15:03:32 +01:00
|
|
|
|
seeder(context, services);
|
|
|
|
|
});
|
|
|
|
|
|
2017-09-13 14:53:06 +02:00
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|