Open Closed

Apply migrations (update database) on application start #6960


0
digitalcontrol created

Is it posible to automatically apply migrations (update database) on application start? I tried with context.Database.Migrate() but I am getting an error - "System.InvalidOperationException: 'The connection is already in a transaction and cannot participate in another transaction.'"


4 Answer(s)
  • 0
    maliming created

    Where do you call context.Database.Migrate()? Please share some code.

  • 0
    digitalcontrol created

    I've tried to call that method on a few places

    - in Startup.cs Configure method

    using (var scope = app.ApplicationServices.CreateScope()) { scope.ServiceProvider.GetService<DatabaseUpdateHelper>().Update(); }

    - in RIMIKSXEntityFrameworkCoreModule.cs in PostInitialize using (var scope = IocManager.CreateScope()) { scope.Resolve<DatabaseUpdateHelper>().Update(); }

    - I tried in PreInitialize and Initialize but didn't work either

    RIMIKSX.EntityFrameworkCore.DatabaseUpdateHelper is helper class with one method Update which calls context.Database.Migrate()

  • 1
    maliming created

    Try using IAbpZeroDbMigrator under the PostInitialize method of XXXEntityFrameworkCoreModule.

    public override void PostInitialize()
    {
    	using (var scope = IocManager.CreateScope())
    	{
    		scope.Resolve<IAbpZeroDbMigrator>().CreateOrMigrateForHost();
    	}
    
    	var configurationAccessor = IocManager.Resolve<IAppConfigurationAccessor>();
    
    	using (var scope = IocManager.CreateScope())
    	{
    		if (!SkipDbSeed && scope.Resolve<DatabaseCheckHelper>().Exist(configurationAccessor.Configuration["ConnectionStrings:Default"]))
    		{
    			SeedHelper.SeedHostDb(IocManager);
    		}
    	}
    }
    
    
  • 0
    digitalcontrol created

    Yes, it works thank you!!