準備
Dockerがインストールされた Linux サーバーが必要です。または、Docker Desktop for Windows を使用してください。
データベースをインストールする
sudo apt update
sudo apt install postgresql postgresql-contri
インストールを確認する
sudo -u postgres psql -c "SELECT version();"
データベースを作成する
sudo su - postgres -c "createdb [数据库名]"
postgres パスワードを追加
sudo su - postgres -c "ALTER USER postgres WITH PASSWORD '[密码]';"
設定を変更
cd /etc/postgresql/12/main
sudo nano postgresql.conf
# - Connection Settings - 节
listen_addresses = '*'
すべてに開かれている
sudo nano pg_hba.conf
host all all 0.0.0.0/0 md5
リブート
sudo service postgresql restart
確認
ss -nlt | grep 5432
クライアントをインストールする
データベースの使用
创建类库Postgre.Data
创建控制台 Postgre.Helloworld
Postgre.Data は、codefirst に EntityFramwork Core 6.x を使用します
パッケージマネージャーを使用して、インストール
Install-package Microsoft.EntityFrameworkCore.Tools
PostgreSQL への参照を追加する
nuget 添加 Npgsql.EntityFrameworkCore.PostgreSQL
myContext を追加
public class MyContext : DbContext
{
public MyContext() : base()
{
}
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
public DbSet<ProjectScanResult>? ProjectScanResults { get; set; }
public DbSet<ProjectScanHistory>? ProjectScanHistorys { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//if (!optionsBuilder.IsConfigured)
//{
// var connectionString = @"User ID =postgres;Password=xxxx;Server=xxx.xxx.xxx.xxx;Port=5432;Database=xxxx;Integrated Security=true;Pooling=true;";
// optionsBuilder.UseNpgsql(connectionString);
//}
}
}
Postgre.Helloworld コード構成 (DotNet 6 Program.cs)
//Database configuration
builder.Services.AddEntityFrameworkNpgsql().AddDbContext<MyContext>(optionsAction: opt =>
{
opt.UseNpgsql(builder.Configuration.GetConnectionString(name: "Conection"));
});
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
//Database initialization
using (var serviceScope = app.Services.GetService<IServiceScopeFactory>()?.CreateScope())
{
var context = serviceScope?.ServiceProvider.GetRequiredService<MyContext>();
context?.Database.Migrate();
}