2
1

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 3 years have passed since last update.

LinqPad: PostgreSQL のデータ操作を EF Driver で

Last updated at Posted at 2021-09-16

やりたかったこと

  • LinqPad から PostgreSQL に、Insert/Update/Deleteといった操作を行いたい

背景

Power BI のデータソースで PostgreSQL を指定された。Sample Data は無く Create用 SQL だけは更新されて渡される。
LinqPad でSampleDataでも作るかと思ったところ・・

  • Linq to DB だとClassとか諸々用意必要で、Schema変更の度に修正が必要で面倒・・
    image.png

で、Entity Framework Core Driver を使うことにしたというお話
image.png

環境

概要

  1. PostgreSQL から DB First で DbContext を生成し、適当にBuildして Exe/Dll を用意しておく
  2. Linq Pad で 作成した Exe を取り込んで接続

PostgreSQL から DB First で DbContext を生成し、適当にBuildして Exe/Dll を用意しておく

適当なProjectで、以下二つを nuget から取得

  • Microsoft.EntityFrameworkCore.Tools
  • Npgsql.EntityFrameworkCore.PostgreSQL
    image.png

対象となる Postgres の設定を使って、Scaffoldを実施

  • "Force" の理由
    • Create.sql が更新されてくる為、Schema 毎削除して実施(コマンドは後述)する為、強制上書きとしている
Scaffoldコマンドの例
Scaffold-DbContext "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=postgres;" Npgsql.EntityFrameworkCore.PostgreSQL -o DbModels -Force

複数形にしたくない場合

-NoPluralize

詳細は以下で

Linq Pad で 作成した Exe を取り込んで接続

Entity Framework Core で接続する
image.png

接続設定は生成した Dll を参照すると、内部の DbContext を選択出来るので、それを選択
※Connection String を別途ここで指定することも可能。
image.png

実際の Add/Remove

こんな感じで Add/Remove が出来るので、Sample Data をC#で生成して Power BIで分析がしやすくなりますね。
image.png

テストTableは以下で紹介されている Create を利用

あとがき

.Net 4の頃のように、ADO.Net Entity Data Model の追加でいけるかと思ったけど、以下エラー。Core 3ではそもそもメニューにはなかった記憶なので、そのうち対応されると期待 → コマンド入力不要になる?
image.png
image.png

PostgreSQL を Power BI のデータソースとした際に利用した SQL

全Table削除 SQL

Create 用のSQLが更新して渡されてくるので、SQL実行前に Schema 毎削除する為のコマンド

DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

keyword

"Add" and "Remove" commands in LinqPad with PostgreSQL

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?