EntityFramework Core automatic migrations

68,113

Solution 1

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

eg:

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

Solution 2

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

Solution 3

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();
        ...
    }
}

Solution 4

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>();
}

Solution 5

My working automigration code 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  
        }
    }
Share:
68,113

Related videos on Youtube

Lapenkov Vladimir
Author by

Lapenkov Vladimir

At work full stack developer .Net Core microservices plus front (Vue ,Angular + React course). Engaged in database development on MSSQL &amp; Oracle. Since 2016 has developed some projects for Android. At home: Like to apend time with children, do some sport &amp; travel.

Updated on July 09, 2022

Comments

  • Lapenkov Vladimir
    Lapenkov Vladimir almost 2 years

    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

    • Tseng
      Tseng over 7 years
      It's called EntityFramework Core 1.0, thanks
  • Lapenkov Vladimir
    Lapenkov Vladimir over 7 years
    MyContext looks this way , I don't know what to put in options public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
  • Frank Odoom
    Frank Odoom over 7 years
    Refer to this article to see how you can manually configure your context stackoverflow.com/questions/38417051/… and github.com/aspnet/EntityFramework/issues/6493
  • Lapenkov Vladimir
    Lapenkov Vladimir over 7 years
    I do the following way in Startup.cs : Startup::Configure after defining routes i add : var options = new DbContextOptionsBuilder<ApplicationDbContext>(); options.UseSqlServer(Configuration.GetConnectionString("Defa‌​ultConnection")); using (var context = new ApplicationDbContext(options.Options)) { context.Database.Migrate(); } but this doesn't perform migrations
  • Frank Odoom
    Frank Odoom over 7 years
    Register your context with dependency injection docs.efproject.net/en/latest/platforms/aspnetcore/new-db.htm‌​l
  • Lapenkov Vladimir
    Lapenkov Vladimir over 7 years
    I registered it this way : services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Defa‌​ultConnection")));
  • Frank Odoom
    Frank Odoom over 7 years
    download a simple sample from this repository..this uses Package Manager Console Scripts...hope it helps :-) github.com/dotnetjalps/EntityFrameworkCoreMigration
  • Arwin
    Arwin over 7 years
    Be that as it may, it worked perfectly for me in all the projects I worked on, resulting in extremely low-fuss maintenance especially during the build-up of a project. Shame that it is gone, but I can imagine sometimes the overhead wasn't worth it.
  • ProfK
    ProfK almost 7 years
    Why are you using an array if you only access the element at 0?
  • Mentor
    Mentor almost 7 years
    in order to have one field for the lock and a quick check without unboxing.
  • Afshar Mohebi
    Afshar Mohebi over 6 years
    Still no chance for automatic migrations to be supported in EF Core 2.0 in Sep. 2017?
  • Sampath
    Sampath over 6 years
  • Afshar Mohebi
    Afshar Mohebi over 6 years
    Thank you @Sampath, the link provides an alternative instead of automatic migrations, if I am understanding correctly. My team needs automatic migration in production enviroment rather than dev environment.
  • Sampath
    Sampath over 6 years
    Oh..OK, Actually I'm not using this tech stack now due to now I'm working only on Ionic mobile apps.But according to my post's link, they labeled it as closed-wont-fix @Afshar
  • Akash Kava
    Akash Kava over 6 years
    @FrankOdoom Answer is wrong, unless individual migration steps are added, Migration does not work and it is not equivalent of AutomaticMigrationsEnabled
  • eka808
    eka808 over 5 years
    When the model changes a lot and and multiple people work on the same project, migrations leads more problems than solutions. Moreover, having thousands of migrations makes the build slower and complicated for no reason. In this context, automatic migration seems the more reasonnable approach.
  • Rosdi Kasim
    Rosdi Kasim over 4 years
    They no longer do this. I have checked their source code.
  • Ali Dehghan Tarzeh
    Ali Dehghan Tarzeh over 4 years
    @Sampath What you consider as "Automatic Migrations" is not what is meant by this question. Here, what they mean is "to update the database on the production server on the first run of the application, whenever the developer makes a change to the data structure by creating and running a manual migration", which could be simply done (as is mentioned in other answers here), but the thing EF Core does not support, is, "to update the database automatically whenever there's a change in the data structure, without creating a manual migration". There's a big difference between the two!
  • Ali Dehghan Tarzeh
    Ali Dehghan Tarzeh over 4 years
    Here's a link to the full instructions for running the manually-created migrations on the server automatically: blog.rsuter.com/…
  • Sampath
    Sampath over 4 years
    @AliDehghanTarzeh Those are not official. See the official link: github.com/aspnet/EntityFrameworkCore/issues/6214
  • karunakar bhogyari
    karunakar bhogyari about 4 years
    context.Database.Migrate(); will update the database based on the migrations you have created.So do not forget to add migrations.
  • Gert Arnold
    Gert Arnold almost 4 years
    Probably not tested before posting.
  • Daniel
    Daniel over 3 years
    This is a duplicate of @Matt-Morgan's answer above. Although the timestamp of your original answer is 2017-02-17, you added the scoped dependency injected dbcontext solution in 2018-06-07, while Matt published the same answer 2017-04-20.
  • Johnny Oshika
    Johnny Oshika over 3 years
    This technique works well for me. Thank you!
  • Naveen Kumar V
    Naveen Kumar V about 3 years
    Worked for me :)
  • Jucko Thirteen
    Jucko Thirteen almost 3 years
    All the examples were for ASP .NET. But finally, this method works for C# 5 with EFCore. This took me hours to figure out...
  • kaptcha
    kaptcha about 2 years
    Can this work with Postgres or just SQL Server?
  • Ionut N
    Ionut N about 2 years
    This package is designed to work only with Sql Server.