PostgreSQL で Dapper を使う

.NET Server Framework がリリースされたら、Mac OS XLinux で動く .NET アプリケーションを作ることもありそう。そうなるとデータベースは PostgreSQL かなぁ。My SQLMariaDB も捨てがたい。

どちらにしても、ORM には Dapper か Entity Framework を使うと思うので、まずは PostgreSQL と Dapper の組み合わせを試してみる。

新規コンソールアプリケーションプロジェクトに NuGet で

  • Npgsql
  • Dapper

を追加し、Npgsql と Dapper を使ったサンプルを書いてみた。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Dapper;
using Npgsql;

namespace DapperSample
{
    public class Bookmark
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Comment { get; set; }
        public string Url { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 接続文字列を作成
            var builder = new NpgsqlConnectionStringBuilder()
            {
                Host = "localhost",
                Port = 5432,
                Database = "postgres",
                UserName = "postgres",
                Password = "postgres",
            };

            // TransactionScope を使って自動ロールバックする
            using (var ts = new TransactionScope())
            using (var connection = new NpgsqlConnection(builder))
            {
                connection.Open();

                // テーブル作成
                connection.Execute(
                    @"create table Bookmarks (
                          Id      serial primary key,
                          Title   varchar(100),
                          Comment text,
                          Url     varchar(250)
                      )"
                );

                // データ挿入
                connection.Execute(
                    @"insert into Bookmarks (
                          Title,
                          Comment,
                          Url
                      )
                      values (
                          'present',
                          '技術ブログ',
                          'http://tnakamura.hatenablog.com'
                      )"
                );

                // データ取得
                var bookmarks = connection.Query<Bookmark>(@"select * from Bookmarks");
                foreach (var b in bookmarks)
                {
                    Console.WriteLine(b.Id.ToString());
                    Console.WriteLine(b.Title);
                    Console.WriteLine(b.Comment);
                    Console.WriteLine(b.Url);
                    Console.WriteLine();
                }

                // テーブル削除
                connection.Execute("drop table Bookmarks");
            }

            Console.WriteLine("Enter で終了");
            Console.ReadLine();
        }
    }
}

f:id:griefworker:20150106095634p:plain

PostgreSQL でも Dapper 使えそうだ。