0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Visual Studio 2017でNpgSqlとEntityFrameworkを使ってみた

Posted at

インストール

NuGetを使って、npgsqlとEntityFramework6.Npgsqlをインストール
検索して、見つかったのを選んでインストールで問題なく完了

npgsql.orgのGetting Started(https://www.npgsql.org/doc/index.html)を見て、App.configに追記を行う。

DBテーブルに対応するエンティティクラスを作成

DBテーブルの内容に対応したエンティティクラスを作成。
[Table("テーブル名")]、[Key]、[Column("フィールド名")]、[Required]等を使います。
Requiredが not null に対応。
https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations
を参照。

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

https://creatorhyp.com/tips/program/entity-framework-install/
を参考にしてContextクラスを作成。
System.Data.Entity の DbContextを用いて拡張。上の例と変えたのはContextクラスのコンストラクタの引数を(接続文字列, スキーマ文字列="public")として作成しました。

起こった問題

スキーマ文字列

 上で、スキーマ文字列をpublicとしています。これは、pgAdminでCreate Table SQLを作ってみたところ public.tableName となっていたことと、別の文字列(Schema)で動かしてみたところ、 Schema.tableName がないというエラーが出たためにこうしています。

 検索用のSQLを作成する際にテーブル名が
   スキーマ文字列.[Table()]で指定したテーブル名 
 となるため、設定しています。DB側で別の名前が使われている場合あh調整が必要です。

接続できない?

 当初、EntityFrameworkではなく、お試しでODBC接続を用いたNpgsqlConnectionで開こうとしたところ、なぜか接続できない。
 調べてみたところ、

  1. インストールしてあったpostgreSQLのODBCドライバーが64bit用
  2. プログラムのビルド設定が 任意のCPU だったものの「32bitを優先」にチェックが付いていた
     ビットのConflictが発生していると想定して任意のCPUをx64に切り替えたところ、問題なく接続できるようになりました。
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?