how to use auto migration in entity framework core 2

asp.net-core entity-framework-core

Question

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.

1
2
10/28/2019 6:04:27 AM

Accepted Answer

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();
        }
    }
}
2
10/28/2019 9:33:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow