LoginSignup
0
0

More than 1 year has passed since last update.

ASP.NET CoreでPostgreSQL上にテーブルを作成する手順

Posted at

はじめに

この記事は、ASP.NET CoreでPostgreSQL上にテーブルを作成する手順を記載した記事である。

環境

  • OS:Windows11
  • IDE:Microsoft Visual Studio Community 2022 (64 ビット) - Current Version 17.4.4
  • プロジェクトテンプレート:ASP.NET Core Webアプリ(Model-View-Controller)
  • フレームワーク:.NET7.0(標準用語のサポート)
  • PostgreSQL:15.1

手順

  1. 「ツール」→「NuGetパッケージマネージャー」→「ソリューションのNuGetパッケージの管理」を選択
  2. 「参照」タブをクリックし、検索欄に「npgsql」と入力し検索
  3. 「Npgsql.EntityFrameworkCore.PostgreSQL」を選択し、画面右側のプロジェクトにチェックを入れ、インストールを押下
    image.png
  4. appsettings.jsonを下記のように修正する
    appsettings.json
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        // --------変更_start--------
        "WebApplication4Context": "Host=[PostgreSQLのホスト名];Database=[PostgreSQLのDB名];Username=[PostgreSQLのユーザー名];Password=[PostgreSQLのパスワード]"
        // --------変更_end--------
      }
    }
    
  5. Program.csを下記のように修正する
    Program.cs
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    using WebApplication2.Data;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    var connectionString = builder.Configuration.GetConnectionString("WebApplication4Context") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    
    // --------変更_start--------
    builder.Services.AddDbContext<WebApplication4Context>(options =>
        options.UseNpgsql(connectionString));
    // --------変更_end--------
    // 以降、省略
    
    
  6. SQLServcerと同様、マイグレーションを実施
    Add-Migration InitialCreate
    Update-Database
    
  7. pgadminで確認すると、テーブルが作成されている
    image.png
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0