寫 SideProejct 剛好有資料庫的需求,Heroku 有提供免費的 PostgreSQL 方案可以使用.
環境
- ASP.NET 5(Blazor App)
- Heroku PostgreSQL
Heroku
必須先有一個Heroku的帳號,接著建立一個 App

在 App 內的 Resource 的 Add-ons 找到 Heroku PostgreSQL

將 Heroku PostgreSQL
加入 App,這邊可以選擇方案(價錢),正好就有 Free 的方案可以使用(詳細的規格內容可以從這邊查看)

新增後在 Resource 裡面就有 PostgreSQL 可以使用

點進去後,在 Settings
的 Database Credentials
裡面就是我們需要的連線內容

ASP.NET
建立專案,並加入 nuget package
- Microsoft.EntityFrameworkCore
- Npgsql.EntityFrameworkCore.PostgreSQL
準備好一個 DbContext
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasDefaultSchema("MySchema");
builder.ApplyConfiguration(new ProductConfig());
base.OnModelCreating(builder);
}
}
在 Startup 加入 DbContext
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseNpgsql(Configuration.GetConnectionString("MyDb"),
optionsBuilder =>
{
// Heroku PostgreSQL 必須使用 SSL
// 如果沒設定這行,會在連線時拿到 SSL off 的錯誤
optionsBuilder.RemoteCertificateValidationCallback(
(_, _, _, _) => true);
});
});
}
}
在 AppSetting 加上連線字串,這邊必須加上 SslMode=Require
{
"ConnectionStrings": {
"MyDb": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;SslMode=Require;"
}
}
接著試著連線並取得資料


成功
