EF Core Migration with aspnetboilerplate Where to trigger context.Database.Migrate();

I need to ensure my application itself is able to upgrade his database model (apply migrations)

In the ABP architecture, where should I make the call to Migrate?

context.Database.Migrate();

As this is a call to a infraestructure logic (Entity framework Core) it should be kept out from domain services and application services.

Thanks in advance

Upvotes: 4

Views: 2048

Answers (2)

Nico M
Nico M

Reputation: 51

I finally found a working solution, for abp 4.3 This code allows your application to apply migrations at startup.

public override void PostInitialize()
{
    var dbContextProvider = IocManager.Resolve<IDbContextProvider<ExtranetDbContext>>();
    var unitOfWorkManager = IocManager.Resolve<IUnitOfWorkManager>();

    using (var unitOfWork = unitOfWorkManager.Begin())
    {
        var context = dbContextProvider.GetDbContext(MultiTenancySides.Host);
        
        //Removes actual connection as it has been enlisted in a non needed transaction for migration
        context.Database.CloseConnection();
        context.Database.Migrate();
    }

    if (!SkipDbSeed)
    {
        SeedHelper.SeedHostDb(IocManager);
    }
}

Details about the IUnitOfWorkManager can be found here.

Upvotes: 5

Alper Ebicoglu
Alper Ebicoglu

Reputation: 9644

Hi you can execute database migrations in PostInitialize method in EntityFrameworkCoreModule.

 public class MyApplicationEntityFrameworkCoreModule : AbpModule
    {

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }

            // --> You can execute migrations here <--
        }
    }

Upvotes: 1

Related Questions