Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use auto migration in entity framework core 2

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.

like image 596
ssmmoo Avatar asked Nov 19 '25 11:11

ssmmoo


1 Answers

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();
        }
    }
}
like image 86
Ali Bayat Avatar answered Nov 22 '25 04:11

Ali Bayat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!