[英]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. 在某些测试环境中,我已经配置了应用程序以在数据库不存在时使用Entity Framework迁移创建数据库的新实例。
I am also using Hangfire, and have configured it use SQL Server in my OWIN startup class. 我也在使用Hangfire,并在OWIN启动类中使用SQL Server对其进行了配置。 At present I am instantiating a new instance of my DbContext to force database creation prior to configuring Hangfire to use the database:
目前,我正在实例化我的DbContext的新实例,以在将Hangfire配置为使用数据库之前强制创建数据库:
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. 这感觉有点hacky。 What is the recommended way to ensure Entity Framework has created the database before it is used outside of the DbContext?
在Entity Framework在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: 事实证明,问题中的代码片段本身并不一定足够(取决于平台和其他EF配置设置),因此我们实际上现在在代码中将其明确了(根据Diana的评论),这也使它显得不太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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.