I use entity framework core 2. I saw posts in stack-overflow but I can't resolve my problem. I want to use auto migration in my project without console command.
Try this code:
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
Complete code:
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Services.InitializeDb();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{//Add Code }
}
}
public interface IDbInitializer
{
void Initialize();
}
public class DbInitializer : IDbInitializer
{
private readonly IServiceScopeFactory _scopeFactory;
public DbInitializer(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Initialize()
{
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
}
}
public static class DbContextOptionsExtensions
{
public static void InitializeDb(this IServiceProvider serviceProvider)
{
var scopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var dbInitialize = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
dbInitialize.Initialize();
}
}
}