Automated EntityFramework Core Migrations

Is there any code for automatic migration in Entity Framework core code first in asp.net core project?

I do it simply in MVC4 / 5 by adding

 Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppDbContext, MyProject.Migrations.Configuration>()); public Configuration() { AutomaticMigrationsEnabled = true; } 

This saves time when entities change.

+17
source share
8 answers

You can call context.Database.Migrate() in Startup.cs

eg:

 using (var context = new MyContext(...)) { context.Database.Migrate(); } 
+16
source

EF core does not support automatic migrations . Therefore, you must do this manually.

From the point of view of automatic migrations as a function, we are not planning to implement it in EF Core, as experience has shown that the migration code base is a more manageable approach.

You can read the full story here: Do not perform automatic migrations

+19
source

So they do it in IdentityServer4 http://identityserver.io

 public void ConfigureServices(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("DefaultConnection"); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; // Add framework services. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); ... } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // this will do the initial DB population InitializeDatabase(app); } private void InitializeDatabase(IApplicationBuilder app) { using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate(); scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate(); ... } } 
+14
source

Automatic migration is not supported in EF Core. Migration must be created by hand. To automatically apply all existing migrations manually, you must add the following code to the DbContext:

 public sealed class MyDbContext : DbContext { private static readonly bool[] _migrated = { false }; public MyDbContext( DbContextOptions<MyDbContext> options ) : base( options ) { if ( !_migrated[0] ) lock ( _migrated ) if ( !_migrated[0] ) { Database.Migrate(); // apply all migrations _migrated[0] = true; } } } 

It is not elegant, but it works.

Update for EFCore 2.1:

 public class Program { public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<MyDbContext>(); context.Database.Migrate(); // apply all migrations SeedData.Initialize(services); // Insert default data } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } 
+5
source

After Microsoft documentation

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

If you are using dependency injection, you first need to set the static Data / DbInitializer.cs class and add the following code:

 public static class DbInitializer { public static void Initialize(ApplicationDbContext context) { context.Database.Migrate(); // Add Seed Data... } } 

Note that you can also add seed data.

Then in the Program.cs file add the following code

 public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var environment = services.GetRequiredService<IHostingEnvironment>(); if (!environment.IsDevelopment()) { var context = services.GetRequiredService<ApplicationDbContext>(); DbInitializer.Initialize(context); } } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); } 

In my case, I check the environment to make sure I'm in development, so I can control the migration / updates. However, in production, I want them to be automatic for continuous integration. As others have noted, this is probably not the best practice, but it works great on small projects.

+3
source

My working migration code is Asp Net Core 2.0.7.

  // startup.cs public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // configure app SeedData.Initialize(app.ApplicationServices); } // dbInitializer.cs public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var serviceScope = serviceProvider.CreateScope()) { var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>(); // auto migration context.Database.Migrate(); // Seed the database. InitializeUserAndRoles(context); } } private static void InitializeUserAndRoles(ApplicationDbContext context) { // init user and roles } } 
0
source

You can call Database.Migrate() in the DB context constructor.

0
source

my best advice is not to use automatic migration. It’s always better to add manual migrations, as well as avoid mass migration and follow best practices for manual migration.

automatic migration is not a magic tool, and there will be several cases when you want to add some additional changes to the migration. You only perform using manual migration.

To enable migration, enter "enable-migrations" in the package manager console

Thus, you will have full control over updating or downgrading the database, as well as easy to track migration.

Just three simple steps in the package manager console.

1) add-migrations [some name for your migration]

2) migrations are created for changes, you are viewing them, and you can also make changes to it

3) The updated database is now complete.

migration handling is less painful!

-2
source

All Articles