Created
February 3, 2014 05:48
-
-
Save devlights/8779382 to your computer and use it in GitHub Desktop.
Dapper .NETのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Dapperを利用するにはパッケージマネージャコンソールで | |
// Install-Package Dapper | |
// と入力して、予めライブラリをプロジェクトに参照設定しておきます。 | |
// | |
namespace DapperSample | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
// Dapperを利用するためのusing文. | |
using Dapper; | |
// サンプルデータベース用 | |
using System.Data.SQLite; | |
class Program | |
{ | |
static void Main() | |
{ | |
(new Program()).Go(); | |
} | |
public void Go() | |
{ | |
// | |
// DapperはSystem.Data.DbConnectionオブジェクトに | |
// いくつか便利な拡張メソッドを追加してくれます。 | |
// | |
// 他のORマッピングライブラリと違い、Dapperの場合 | |
// データベースへの接続は自分でやっておく必要があります。 | |
// 以下では、サンプルデータベースとして「SQLite」を利用しています。 | |
// | |
var builder = new SQLiteConnectionStringBuilder | |
{ | |
DataSource = "test.db", | |
LegacyFormat = false, | |
Version = 3, | |
SyncMode = SynchronizationModes.Off, | |
JournalMode = SQLiteJournalModeEnum.Wal | |
}; | |
using (var connection = new SQLiteConnection(builder.ToString())) | |
{ | |
// コネクション確立. | |
connection.Open(); | |
// テスト用スキーマ作成 | |
CreateSampleSchema(connection); | |
// | |
// コネクションが確率できたら、Dapperを利用できます。 | |
// 通常、ADO.NETをそのまま利用する場合、クエリを発行したりしようとすると | |
// | |
// (1) DbCommandオブジェクトを作る | |
// (2) CommandTextプロパティにクエリを設定 | |
// (3) トランザクションを開く (オプション) | |
// (4) ExecuteNonQueryかExecuteReaderを実行 | |
// (5) 結果をループして取得 (しかもキャストしながら) | |
// | |
// という風になります。Dapperを利用すると以下のようになります。 | |
// | |
// (1) 必要であればトランザクションを開く (オプション) | |
// (2) ExecuteまたはQueryを実行 | |
// | |
// 大分楽になります。しかも戻りのオブジェクトには | |
// すでに結果がマッピングされた状態で返ってきます。 | |
// さらに、Dapperは他のORマッパーよりも断然速いです。 | |
// (手動でADO.NETの処理を書いたのとほとんど変わりません。) | |
// | |
// よく利用する以下のパターンについて記述します。 | |
// (1) Insert文を発行 | |
// (2) Select文を発行 (マッピングクラスを利用せずに動的オブジェクト取得) | |
// (3) Select文を発行 (マッピングクラスを利用) | |
// | |
// | |
// Insert文を発行. | |
// DMLを発行する場合は、Executeメソッドを利用します。 | |
// | |
using (var tran = connection.BeginTransaction()) | |
{ | |
try | |
{ | |
connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 1, Name = "Name-1" }, tran); | |
connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 2, Name = "Name-2" }, tran); | |
connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 3, Name = "Name-3" }, tran); | |
tran.Commit(); | |
} | |
catch | |
{ | |
tran.Rollback(); | |
} | |
} | |
// | |
// Select文を発行 (マッピングクラスなし) | |
// 通常のORマッピングライブラリでは、結果をマッピングするための | |
// クラスを作成して、そこに値を設定してくれるものが多いですが | |
// Dapperでは、.NETのdynamic型を利用して、動的オブジェクトで | |
// 結果を返してくれる機能があります。これを利用すると、いちいち | |
// データクラスを作らなくても結果を取得できます。 | |
// | |
// クエリの発行は、Queryメソッドで行います。 | |
// | |
dynamic dynamicObj = connection.Query("SELECT id, name FROM table1 LIMIT 1").FirstOrDefault(); | |
Console.WriteLine("Id: {0}", dynamicObj.id); | |
Console.WriteLine("Name: {0}", dynamicObj.name); | |
// | |
// Select文を発行 (マッピングクラスあり) | |
// 通常のORマッピングライブラリと同様に、マッピング対象クラスを | |
// 指定しての、結果取得も出来ます。 | |
// | |
// クエリの発行は、Query<T>メソッドで行います。 | |
// | |
var mappingObj = connection.Query<Table1>("SELECT id, name FROM table1 LIMIT 1").FirstOrDefault(); | |
Console.WriteLine("Id: {0}", mappingObj.Id); | |
Console.WriteLine("Name: {0}", mappingObj.Name); | |
// | |
// 普通にQueryメソッドを呼び出すと, 結果はIEnumerable<T>の形で返ってきます。 | |
// | |
dynamic results = connection.Query("SELECT id, name FROM table1"); | |
foreach (dynamic item in results) | |
{ | |
Console.WriteLine(item); | |
} | |
} | |
} | |
internal void CreateSampleSchema(SQLiteConnection connection) | |
{ | |
try | |
{ | |
connection.Execute("DROP TABLE table1"); | |
} | |
catch | |
{ | |
// noop. | |
} | |
try | |
{ | |
connection.Execute("CREATE TABLE table1 (id integer primary key, name text)"); | |
} | |
catch | |
{ | |
// noop. | |
} | |
} | |
internal class Table1 | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment