我正在构建一个 ASP.Net Core API,但我无法找到从 DBContextOptions 获取连接字符串的方法。
我的 startup.cs 中有 DBContext,如下所示;
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddEntityFrameworkSqlServer()
.AddDbContext<MainContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MainConnection")));
services.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
在我的 Context 类中,我有以下构造函数;
public MainContext(DbContextOptions<MainContext> options) : base(options)
{
}
但是除非我在 DBContext 类的 OnConfiguring 方法中添加一个实际的连接字符串,否则它不起作用,如下所示;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO Move connection string to a secure location
optionsBuilder.UseSqlServer(@"Server= .....");
}
当我调试并检查 Configuration.GetConnectionString("MainConnection") 中的值时,我可以看到 Startup.cs 正在从 appsettings.json 文件中获取正确的连接字符串。
我认为通过 DI 将选项传递给 DbContext 类会传递连接字符串,但 DbContect 类不起作用,除非我在 OnConfiguring 方法中有 optionBuilder.UseSqlServer() 。
我发现这篇 SO 帖子https://stackoverflow.com/questions/33532599/asp-net-5-multiple-dbcontext-problems谈到了使用以下代码从选项属性中提取连接字符串
public ResourceDbContext(DbContextOptions options) : base(options)
{
_connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(_connectionString);
}
但是当我尝试使用它时,我发现options.Extensions中不再有First()方法
所以,我的第一个问题是……
为什么不用在 OnConfiguring 方法中添加连接字符串 DBContext 类不工作
我的第二个问题是...
如果 OnCONfiguring 方法中需要连接字符串,我如何从 DbContextOptions 选项对象中获取它,而不必在 OnConfiguring 方法中显式提供它 --> optionsBuilder.UseSqlServer(@"Server= .....") ;