简体   繁体   中英

How to make Entity Framework create database before using it outside DbContext?

In certain test environments, I have configured my application to create a new instance of it's database using Entity Framework migrations when the database does not already exist.

I am also using Hangfire, and have configured it use SQL Server in my OWIN startup class. At present I am instantiating a new instance of my DbContext to force database creation prior to configuring Hangfire to use the database:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        using (var dbContext = new MyDbContext())
        {
            // Force database creation before configuring Hangfire to use it.
        }

        GlobalConfiguration.Configuration.UseSqlServerStorage("myConnection");
        // ...
    }
}

This feels a bit hacky. What is the recommended way to ensure Entity Framework has created the database before it is used outside of the DbContext?

Turns out that the snippet in the question isn't necessarily enough by itself (depending upon platform and other EF configuration settings), so we actually make it explicit in the code now (as per Diana's comment), which also makes it feel less hacky:

// Trigger database creation before Hangfire tries to use it.
var initializer = new MigrateDatabaseToLatestVersion<MyDbContext, MyConfiguration>(true);
Database.SetInitializer(initializer);
var connectionString = this.Configuration.GetConnectionString("MyConnectionString");
using (var dbContext = new MyDbContext(connectionString))
{
    dbContext.Database.Initialize(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM