在 Asp.Net 核心应用程序中,无法从 json 文件中读取连接字符串?
in an Asp.Net core application, Unable to read the connection string from the json file?
https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings?
我按照此站点将连接字符串放入 json 文件中,但是当我尝试访问数据库时说我想获取所有酒店的列表,但出现异常 "Value cannot be null"
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("ConnectionServerJson.json")
.AddEnvironmentVariables();
configuration = builder.Build();
}
public IConfiguration configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBRezervareHotelieraContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<DbContext>(sp => sp.GetService<DBRezervareHotelieraContext>());
var container = services.BuildServiceProvider();
services.AddMvc();
}
这是 connectionStringJson.json 文件
{
"connectionString": {
"DefaultConnection": "Server=DESKTOP-TPPITPA\SQLEXPRESS;Database=DBRezervareHoteliera;Trusted_Connection=True;"
}
}
我也确实从上下文中取出class DBRezervareHotelieraContext
onConfigure
方法并放入以下内容
public
DBRezervareHotelieraContext(DbContextOptions<DBRezervareHotelieraContext> options) : base(options)
{
}
我认为这无关紧要,但可能会有帮助
您需要在配置文件中 "ConnectionString" 的末尾添加一个 "s":ConnectionStrings
并将案例命名为 PascalCase。
https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings?
我按照此站点将连接字符串放入 json 文件中,但是当我尝试访问数据库时说我想获取所有酒店的列表,但出现异常 "Value cannot be null"
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("ConnectionServerJson.json")
.AddEnvironmentVariables();
configuration = builder.Build();
}
public IConfiguration configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBRezervareHotelieraContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<DbContext>(sp => sp.GetService<DBRezervareHotelieraContext>());
var container = services.BuildServiceProvider();
services.AddMvc();
}
这是 connectionStringJson.json 文件
{
"connectionString": {
"DefaultConnection": "Server=DESKTOP-TPPITPA\SQLEXPRESS;Database=DBRezervareHoteliera;Trusted_Connection=True;"
}
}
我也确实从上下文中取出class DBRezervareHotelieraContext
onConfigure
方法并放入以下内容
public
DBRezervareHotelieraContext(DbContextOptions<DBRezervareHotelieraContext> options) : base(options)
{
}
我认为这无关紧要,但可能会有帮助
您需要在配置文件中 "ConnectionString" 的末尾添加一个 "s":ConnectionStrings
并将案例命名为 PascalCase。