LoginSignup
22
19

More than 5 years have passed since last update.

Entity FrameworkでPostgreSQLに接続する

Posted at

丸一日はまった。SQLServerの場合全部勝手にやってくれてる最初の処理を全部書かないといけなかったからなんですが。
手間が減るのは万々歳なんだけど、中身の理解を後回しにしてしまうという点で善し悪し。

環境・テーブル構造・フォームのコードについてはEntityFramework6で単純なデータ表示フォームを作成と同じ。

データベースはPostgreSQL9.4を使用

パッケージインストール

NugetよりEntityFramework6.Npgsqlをインストール。
依存関係は全部引っ張ってきてくれます。

App.configの編集

<configration>セクション内に以下を追記

App.condig
  <connectionStrings>
    <add name="接続名"
      connectionString="接続文字列"
      providerName="Npgsql" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <add name="Npgsql
        Data Provider"
        invariant="Npgsql"
        support="FF"
        description=".Net Framework Data Provider for Postgresql"
        type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>
  </system.data>

エンティティクラスの作成

Model.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Postgresql_DBtoCode.Database
{
    [Table("model")] //テーブル名
    class Model
    {
        [Key] //主キー列の宣言
        [Column("model_id")] //列名
        public int ModelID { get; set; }

        [Column("model_name")]
        public string ModelName { get; set; }
    }
}
Title.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace Postgresql_DBtoCode.Database
{
    [Table("title")]
    class Title
    {
        [Column("title_id")]
        public int TitleID { get; set; }

        [Column("model_id")]
        public int ModelID { get; set; }

        [Column("version_id")]
        public decimal VersionNO { get; set; }

        [Column("title_name")]
        public string TitleName { get; set; }

        [Column("running_date")]
        public DateTime RunningDate { get; set; }

        [ForeignKey(nameof(ModelID))] //外部キー列の指定 *プロパティ名を指定する
        public Model Model { get; set; }
    }
}

コンテキストクラスの作成

MusicGameData.cs
using System.Data.Entity;

namespace Postgresql_DBtoCode.Database
{
    class MusicGameData : DbContext
    {
        public MusicGameData()
            : base("name=接続名")
        {
        }

        public DbSet<Model> Models { get; set; }
        public DbSet<Title> Titles { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("スキーマ名");
        }
    }
}

とりあえずこれで前回のコードが動きます。やってることはただのベタ書き。

22
19
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
22
19