builder.Services.AddDbContext
如何为 pgadmin 4 添加连接字符串,上面一个是针对 sqlserver 的
pgadmin4
不是数据库,请问如何连接PostgreSQL?
首先需要添加NuGet包:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
然后,你需要在
connectionstring
中添加appsettings.json
:
{
"ConnectionStrings": {
"WebApiDatabase": "Host=localhost; Database=xxx; Username=xxx; Password=xxx"
},
}
最后这样配置:
services.AddDbContext<xxxContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("ConnectionStrings")));
对于 Program.cs
builder.Services.AddEntityFrameworkNpgsql().AddDbContext<ApiDbContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("SampleDbConnection")));