差分

ナビゲーションに移動 検索に移動

Dapper

2,316 バイト追加, 2012年3月7日 (水) 05:12
編集の要約なし
'''Dapper'''とは、俗にいうMicro ORM。
SQL周りのソースコードがまるでPHPのように書ける。
 
公式サイトではSQL ServerとSQL Liteで動作確認をしているとのことだが、MySQL([[MySQL Connector/NET]])でもちょろっと使ってみた限りでは特に問題はない模様。
 
== 使い方 ==
=== SELECT ===
<source lang="csharp">
public class UserRawModel
{
public string user_id { get; set; }
public string user_name { get; set; }
// nullable
public int? user_age { get; set; }
}
 
var guid = Guid.NewGuid();
 
var user = connection.Query<UserRawModel>(
@"select user_age = @user_age, user_id = @user_id"
, new { user_age = (int?)null, user_id = guid });
 
Console.WriteLine(dog.Count()); // 1
Console.WriteLine(dog.First().user_age); // null
Console.WriteLine(dog.First().user_id); // guid
</source>
 
=== SELECT ===
結果が匿名型で自動生成されます。
まるでPHPのように扱いたいひと向け。
 
インテリセンスが効かない、参照先・参照元の一覧出力ができないなどの副作用を伴うので乱用はやめた方がいいけど、手軽すぎてやめられない。
前述の理由でクラスとテーブルが1対1で問題ない場合は使うべきではないですが、joinした結果を受け取りたい場合などにそのためだけに専用のマッピングクラスを作るのは面倒なのでこれを使うと手軽。
 
クエリー
<source lang="mysql">
select 1 A, 2 B union all select 3, 4;
</source>
結果
<pre>
+---+---+
| A | B |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
</pre>
 
これを取得するコード。
<source lang="csharp">
var rows = connection.Query("select 1 A, 2 B union all select 3, 4")
.ToList(); // 配列(リスト)に変換
 
Console.WriteLine(rows[0].A);
Console.WriteLine(rows[0].B);
Console.WriteLine(rows[1].A);
Console.WriteLine(rows[1].B);
</source>
 
=== INSERT ===
<source lang="csharp">
// {1,1},{2,2},{3,3}という3行がinsertされる
// 戻り値は変更された行数
var affected_rows = connection.Execute(
@"insert MyTable(colA, colB) values (@a, @b)",
new[] { // パラメータを配列にすると複数行をinsertできます。
new { a=1, b=1 },
new { a=2, b=2 },
new { a=3, b=3 }
}
);
</source>
== 関連項目 ==
* [[System.Transactions.TransactionScope]]
* [[MySQL Connector/NET]]
== 外部リンク ==
* 公式サイト - http://code.google.com/p/dapper-dot-net/
* ソースコード - https://github.com/SamSaffron/dapper-dot-net
 
{{stub}}
匿名利用者

案内メニュー