Sunday, 26 January 2025

Apply Migration and DB schema if not exist while run local

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();

          // Ensure the database is created and apply migrations if it is empty
          using (var scope = app.ApplicationServices.CreateScope())
          {
              var dbContext = scope.ServiceProvider.GetRequiredService<DbContext>();


              // Retrieve the IRelationalDatabaseCreator service from the service provider
              var databaseCreator = dbContext.Database
                                .GetService<IRelationalDatabaseCreator>();

              // Check if the database exists, and create it if it doesn't
              // Create the database If SQL server is local.Otherwise don't apply migration and database creation
              if (!databaseCreator.Exists())
              {
                      databaseCreator.Create();
                  // Check if the database has any tables
                  if (!databaseCreator.HasTables())
                  {
                      dbContext.Database.Migrate();
                  }// Apply all migrations
               
              }
             
          }
      }
}

No comments:

Post a Comment