Skip to content

Document where to place code for applying migrations at runtime #2369

Closed

Description

@Eli-Black-Work

The "Apply migrations at runtime" section contains code but doesn't say where in your app to put it. I found the answer at https://stackoverflow.com/a/38263675, but it would be nice if the article mentioned where this code should be placed within your app :)


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Activity

  1. bricelam commented on May 8, 2020

    @bricelam
    Contributor

    If you understand the security risks of using a connection string with permissions to alter the database schema and you understand problems that can occur when multiple instances of your app try to migrate the database at the same time...

    You can do it in Program.Main. If you're using Microsoft.Extensions.Hosting, it would look like this:

    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
    
        using (var scope = host.Services.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            db.Database.Migrate();
        }
    
        host.Run();
    }

    You could also consider adding an admin page that requires the user to be authenticated before clicking a button to migrate the database.

  2. added this to the Backlog milestone on May 9, 2020
  3. added a commit that references this issue on Jun 29, 2020
    2c06834
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions