我有一个ASP .NET MVC 6和Entity Framework 6,分为几层,如何在DbContext的DAL层中获取连接字符串? 连接字符串在appsettings.json文件中,如下所示:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Verbose",
"System": "Information",
"Microsoft": "Information"
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "",
}
}
}
答案 0 :(得分:2)
如果您在appsettings.json
中有连接字符串,则首先要构建配置对象:
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();
这可能应该在Startup
的ctor中。然后,您可以将configuration
对象存储在字段中。让我们说一个_configuration
字段。
然后你可以做
// _connectionString is also a field.
_connectionString = _configuration["Data:DefaultConnection"];
您的DbContext
:
public class AppDbContext : DbContext
{
public AppDbContext(string connectionString) : base(connectionString)
{
}
}
您可以在AppDbContext
注册ConfigureServices
作为:
services.AddScoped(_ => new AppDbContext(_connectionString));