Where should I put Database.EnsureCreated?

前端 未结 3 703
终归单人心
终归单人心 2021-01-11 18:50

I have an Entity Framework Core + ASP.NET Core application and when my application starts up I want to ensure that the database is created, and eventually (once I have migra

相关标签:
3条回答
  • 2021-01-11 19:29

    At the time of this writing, there is not a "correct" place to run code on application startup such that it executes within the request scope (see https://github.com/aspnet/Hosting/issues/373).

    For now, the workaround is to do the following, but it won't work in more complex multi-application scenarios (see https://github.com/aspnet/EntityFramework/issues/3070#issuecomment-142752126)

    public class Startup
    {
        ...
    
        public void Configure(IApplicationBuilder applicationBuilder, ...)
        {
            ...
            // NOTE: this must go at the end of Configure
            var serviceScopeFactory = applicationBuilder.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
            using (var serviceScope = serviceScopeFactory.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService<MyDbContext>();
                dbContext.Database.EnsureCreated();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-11 19:52

    I think zmbq's suggestion is a correct one and there is a way to ensure that migrations are run along with the deployment, so that binaries and database changes are in sync, using Visual Studio's Publish functionality.

    When publishing against an IIS instance, one can specify target database connection string to use to also run required migrations:

    This will ensure that changes are applied only when needed (not every time application starts) and that application runs using the least required database rights (i.e. database writer, reader etc.) as opposed to rights to alter tables, create indexes etc.

    0 讨论(0)
  • 2021-01-11 19:53

    I wonder why you would run to run EnsureCreated as part of your service anyway. Do you really want your webserver to create or update the database schema? Why would the webserver be up and serving request if the database is not up to date?

    Do you really trust your migrations so much that they don't ruin data when executed, that you don't want to test the data after running them?

    In addition, this will require you to give the webserver database user permissions to change the database schema. This is a vulnerability in itself - someone taking over your webserver will be able to modify your database schema.

    I suggest you create the database and apply migrations in a small utility you run yourself, not as part of your web application.

    0 讨论(0)
提交回复
热议问题