我正在嘗試使用ASP.NET Core 1.1應用程序,並試圖從配置文件中讀取連接字符串。從配置文件(appsettings.json)中讀取數據庫上下文的ASP.NET核心運行遷移
我的數據庫上下文類看起來是這樣的:
public class ApplicationDbContext : DbContext, IDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public ApplicationDbContext Create(DbContextFactoryOptions options)
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
string connString = "some hardcoded connection string";
builder.UseSqlServer(connString);
return new ApplicationDbContext(builder.Options);
}
}
運行的遷移工作正常(例如dotnet ef database update
)。
如果我想刪除硬編碼的連接字符串,我面臨着以下問題:
- ,如果我嘗試注入
IConfiguration
爲ApplicationDbContext
,遷移將會失敗No parameterless constructor defined for this object.
- 沒有注入的東西我無法找到一種從配置文件中讀取信息的方式
我該如何繼續?
謝謝。
[編輯]
在Startup.cs
我已經配置的連接字符串,並將其正常工作時(runtime):
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
//services.AddApplicationInsightsTelemetry(Configuration);
string connString = ConfigurationExtensions.GetConnectionString(Configuration, "DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connString));
services.AddMvc();
}
的問題是,dotnet migrations
似乎需要在數據庫環境參數的構造函數並實施IDbContextFactory<>
,我不知道如何注入配置。後
編輯試圖IOptions <>與ApplicationDbContext
我曾嘗試提出解決方案,但我不能讓它工作,因爲dotnet migration
將調用默認的構造函數。
public class ApplicationDbContext : DbContext, IDbContextFactory<ApplicationDbContext>
{
private IOptions<DefaultConnectionValue> ConnOptions;
private string connectionString;
public ApplicationDbContext()
{
Console.WriteLine("Default constructor was called");
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IOptions<DefaultConnectionValue> connOptions) : base(options)
{
ConnOptions = connOptions;
connectionString = connOptions.Value.Value;
Console.WriteLine($"Injected connection string = {connectionString}");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public ApplicationDbContext Create(DbContextFactoryOptions options)
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
//string connString = ConfigurationExtensions.GetConnectionString(null, "DefaultConnection");
builder.UseSqlServer(connectionString);
return new ApplicationDbContext(builder.Options, ConnOptions);
}
但你添加到ConfigureServices:services.AddDbContext(選項=> options.UseSqlServer(Configuration.GetConnectionString(「DefaultConnection」))); https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro –
Alexan
@Alex - 我編輯了我的問題來回答你的問題。 – Alexei