【覚書】ASP.NET Core Razor PagesとPostgreSQLとの接続
■動作環境
・Visual Studio Community 2019
・.NET Core 3.1
■手順
1.Npgsql.EntityFrameworkCore.PostgreSQLをNuGetよりインストール
2.モデルの追加
※例:Models/Appuser
using System.ComponentModel.DataAnnotations.Schema;
namespace AspNetCoreTest.Models
{
[Table("appuser", Schema = "public")]
public class Appuser
{
[Column("appuserid")]
public int AppuserId { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("password")]
public string Password { get; set; }
}
}
3.DbContextの追加
※例:Data/MyContext
using AspNetCoreTest.Models;
using Microsoft.EntityFrameworkCore;
namespace AspNetCoreTest.Data
{
public class MyContext: DbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
public DbSet<Appuser> Appuser { get; set; }
}
}
4.ConnectionStringsの追加
※appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=testdb"
}
}
5.サービスの追加
※Startup.cs
(中略)
public void ConfigureServices(IServiceCollection services)
{
//PostgreSQL接続のために追加
services.AddDbContext<MyContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddRazorPages();
}
(中略)
6.スキャフォールディング
※Pages/Appusers