[英]How to generate usable dbcontext from database using entity framework?
[英]How to make Entity Framework create database before using it outside DbContext?
在某些測試環境中,我已經配置了應用程序以在數據庫不存在時使用Entity Framework遷移創建數據庫的新實例。
我也在使用Hangfire,並在OWIN啟動類中使用SQL Server對其進行了配置。 目前,我正在實例化我的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");
// ...
}
}
這感覺有點hacky。 在Entity Framework在DbContext之外使用之前,要確保實體框架已創建數據庫的建議方法是什么?
事實證明,問題中的代碼片段本身並不一定足夠(取決於平台和其他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.