Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Core automatic migrations

Is there any code to perform 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 changed

like image 997
Lapenkov Vladimir Avatar asked Sep 16 '16 08:09

Lapenkov Vladimir


People also ask

How do I enable auto migration in .NET core?

Run the Enable-Migrations –EnableAutomaticMigrations command in Package Manager Console This command has added a Migrations folder to our project. This new folder contains one file: The Configuration class. This class allows you to configure how Migrations behaves for your context.

How does EF core apply migrations?

Migrations are enabled by default in EF Core. They are managed by executing commands. If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations. Alternatively, you can use a command line tool to execute Entity Framework CLI commands to create a migration.

How do you set Dbmigragrationsconfiguration AutomaticMigrationsEnabled to true to enable automatic migration?

Set DbMigrationsConfiguration. AutomaticMigrationsEnabled to true to enable automatic migration. You can use the Add-Migration command to write the pending model changes to a code-based migration. I tried AutomaticMigrationsEnabled = true , which worked without changing or adding anything!

What is migration in Entity Framework Core?

Entity Framework Core Tutorial Migrations. Migrations provide a way to incrementally apply schema changes to the database to keep it in sync with your EF Core model while preserving existing data in the database. When start developing your applications, you will most likely see changes in your model with change in requirements.

How do migrations work in EF?

At a high level, migrations function in the following way: When a data model change is introduced, the developer uses EF Core tools to add a corresponding migration describing the updates necessary to keep the database schema in sync.

How do I remove a migration from my EF Core Model?

Sometimes you add a migration and realize you need to make additional changes to your EF Core model before applying it. To remove the last migration, use this command. Remove-Migration dotnet ef migrations remove. After removing the migration, you can make the additional model changes and add it again.

How to create an initial database with three entities in Entity Framework?

Let's say we have a simple model containing three entities. Here is the context class. You can use migration to create an initial database by adding initial migration command in Package Manager Console. The InitialCreate is migration name, and it is up to you what you want to specify as a name.


5 Answers

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

eg:

using (var context = new MyContext(...))
{
    context.Database.Migrate();
}
like image 113
Frank Odoom Avatar answered Oct 17 '22 00:10

Frank Odoom


EF core doesn't support automatic migrations.So you have to do it manually.

From the perspective of automatic migrations as a feature, we are not planning to implement it in EF Core as experience has showed code-base migrations to be a more manageable approach.

You can read full story here : Not to implement Automatic Migrations

like image 30
Sampath Avatar answered Oct 16 '22 23:10

Sampath


This is the way 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();
        ...
    }
}
like image 27
Matt Morgan Avatar answered Oct 17 '22 00:10

Matt Morgan


Automatic migrations is not supported in EF Core. Migration it is necessary to create hands. To automatically apply all existing handmade migrations need to add the following code in the class Program:

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>();
}
like image 18
Mentor Avatar answered Oct 17 '22 00:10

Mentor


Following Microsoft's documentation

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

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

public static class DbInitializer
{
    public static void Initialize(ApplicationDbContext context)
    {
        context.Database.Migrate();

        // Add Seed Data...
    }
}

Notice, this is also where you can add seed data.

Next, in your 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'm checking the environment to make sure I'm in development so I can control the migrations/updates. However, in production, I want them to be automatic for continuous integration. As others have mentioned, this is probably not best practices but on small projects it works great.

like image 5
Amac Avatar answered Oct 17 '22 01:10

Amac