![](/img/trans.png)
[英]Why dont my tables get created with this MVC5 configuration inheriting from IdentityDbContext
[英]How to get configuration options into my IdentityDBContext?
當我嘗試僅使用默認構造函數保留數據庫上下文,但在Startup.cs中傳遞連接字符串時,出現錯誤“使用配置調用了AddDbContext,但是上下文類型'ApplicationDbContext'僅聲明了無參數構造函數”。 但是,如果我嘗試通過以下方式在DbContext自身內部構建它:
private readonly IConfiguration _configuration;
public ApplicationDbContext([FromServices]IConfiguration configuration)
{
_configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_configuration["ConnectionString"]);
}
使用“無法創建類型為'ApplicationDbContext'的實例。模型綁定的復雜類型不能為抽象或值類型,並且必須具有無參數構造函數”時,會出現一些抱怨。 如果同時具有兩個構造函數,那么當嘗試訪問_configuration
時,我毫不奇怪地會得到null引用異常。 我覺得這是一個很常見的情況,因此我必須缺少明顯的東西。
編輯
在startup.cs中,這就是我添加DbContext的方式(在ConfigureServices
):
services.AddDbContext<ApplicationDbContext>(/*options => options.UseSqlServer(Configuration["ConnectionString"])*/);
同樣,該類在ConfigureServices
另一處使用:
services.AddIdentity<IdentityUser, IdentityRole>( options =>
{...})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
您可以如下定義一個構造函數:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, [FromServices]IConfiguration configuration)
: base(options)
{
}
兩個參數都應該注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.