フッターコンテンツにスキップ
.NETヘルプ

Dapper C#(開発者向けの動作方法)

現代のソフトウェア開発において、効率的にデータベースにアクセスすることは、アプリケーションのパフォーマンスと拡張性にとって重要です。 Dapperは、.NET用の軽量なオブジェクト関係マッパー(ORM)であり、データベースとのやりとりを合理化するアプローチを提供します。 この記事では、SQLiteデータベースファイルと共にDapper C#を使用する方法を探求し、そのシンプルさと効果をコード例を通じて実証します。 Additionally, I will introduce the remarkable PDF generation library called IronPDF from Iron Software.

Dapperとは何か?

Dapperは、.NETプラットフォーム用のオブジェクト関係マッピング(ORM)フレームワークです。 これは、オブジェクト指向のドメインモデルを従来の関係データベースにマッピングするシンプルなオブジェクトマッパーです。 Dapperはその速度とパフォーマンスで知られており、「マイクロORMの王」としてしばしば言及されます。生のADO.NETデータリーダーと同等の速度で、IDbConnectionインターフェースを拡張してSQLデータベースのクエリに役立つ拡張メソッドを追加します。

Dapperの主な機能

  1. パフォーマンス: Dapperはその軽量な設計と効率的なオブジェクトマッピングのおかげで優れたパフォーマンスで知られています。
  2. シンプルさ: DapperのAPIはミニマリスティックで直感的であり、開発者が簡単に理解し効果的に使用できます。
  3. 生SQLサポート: Dapperは開発者が生のSQLクエリを書くことを可能にし、データベースのやり取りに完全な制御を提供します。
  4. オブジェクトマッピング: Dapperはクエリ結果を直接C#オブジェクトにマッピングし、ボイラープレートコードを減らし、コードの可読性を向上させます。
  5. パラメータ化されたクエリ: Dapperはパラメータ化されたクエリをサポートし、SQLインジェクション攻撃から保護しパフォーマンスを向上させます。
  6. マルチマッピング: Dapperは1対多および多対多の関係をスムーズに処理し、複数のクエリを効率的に実行することができ、複雑なデータの取得を簡略化します。

Dapperによる非同期データアクセス

Dapperは、その同期カウンターパートを反映した非同期拡張メソッドを提供し、開発者がデータベースクエリを非同期で実行できるようにします。 これらの非同期メソッドは、データベースクエリのようなI/Oに依存する操作に最適であり、データベースの操作完了を待つ間、メインスレッドは他のタスクを継続して実行できます。

Dapperの主要な非同期メソッド

  1. QueryAsync: 非同期でSQLクエリを実行し、動的オブジェクトまたは強い型オブジェクトのシーケンスとして結果を返します。
  2. QueryFirstOrDefaultAsync: 非同期でSQLクエリを実行し、最初の結果または結果が見つからない場合はデフォルト値を返します。
  3. ExecuteAsync: 非同期でSQLコマンド(例: INSERT, UPDATE, DELETE)を実行し、影響を受けた行数を返します。

環境のセットアップ: コード例に入る前に、必要なツールがインストールされていることを確認してください:

  1. Visual Studio または Visual Studio Code。
  2. .NET SDK。
  3. .NET用SQLiteパッケージ。

SQLiteパッケージをインストールするには、プロジェクトディレクトリで次のコマンドを実行します:

dotnet add package Microsoft.Data.Sqlite
dotnet add package Microsoft.Data.Sqlite
SHELL

SQLiteデータベースの作成: デモンストレーションのために、「example.db」という名前のSQLiteデータベースファイルを作成し、「Users」テーブルに「Id」、「Name」、および「Email」の列を含めます。

CREATE TABLE Users (
    Id INTEGER PRIMARY KEY,
    Name TEXT,
    Email TEXT
);

SQLiteでDapperを使用する

  1. まず必要な名前空間がインポートされていることを確認します:
using Microsoft.Data.Sqlite;
using Dapper;
using Microsoft.Data.Sqlite;
using Dapper;
Imports Microsoft.Data.Sqlite
Imports Dapper
$vbLabelText   $csharpLabel
  1. SQLiteデータベースへの接続を確立します:

    string connectionString = "Data Source=example.db"; // SQLite database connection string
    using (var connection = new SqliteConnection(connectionString))
    {
        connection.Open();
        // Your Dapper queries will go here
    }
    string connectionString = "Data Source=example.db"; // SQLite database connection string
    using (var connection = new SqliteConnection(connectionString))
    {
        connection.Open();
        // Your Dapper queries will go here
    }
    Dim connectionString As String = "Data Source=example.db" ' SQLite database connection string
    Using connection = New SqliteConnection(connectionString)
    	connection.Open()
    	' Your Dapper queries will go here
    End Using
    $vbLabelText   $csharpLabel
  2. Dapperでクエリを実行します:

    // Define a class to represent the structure of a user
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    
    // Query to select all users
    string query = "SELECT * FROM Users"; // SQL query
    var users = connection.Query<User>(query).ToList();
    
    // Display the results
    foreach (var user in users)
    {
        Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}");
    }
    // Define a class to represent the structure of a user
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    
    // Query to select all users
    string query = "SELECT * FROM Users"; // SQL query
    var users = connection.Query<User>(query).ToList();
    
    // Display the results
    foreach (var user in users)
    {
        Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}");
    }
    ' Define a class to represent the structure of a user
    Public Class User
    	Public Property Id() As Integer
    	Public Property Name() As String
    	Public Property Email() As String
    End Class
    
    ' Query to select all users
    Private query As String = "SELECT * FROM Users" ' SQL query
    Private users = connection.Query(Of User)(query).ToList()
    
    ' Display the results
    For Each user In users
    	Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}")
    Next user
    $vbLabelText   $csharpLabel
  3. Dapperを使用してデータベースにデータを挿入します:

    // Define a new user 
    var newUser = new User { Name = "John Doe", Email = "john@example.com" };
    
    // SQL query/stored procedure to insert a new user
    string insertQuery = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
    
    // Execute the query
    connection.Execute(insertQuery, newUser);
    // Define a new user 
    var newUser = new User { Name = "John Doe", Email = "john@example.com" };
    
    // SQL query/stored procedure to insert a new user
    string insertQuery = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
    
    // Execute the query
    connection.Execute(insertQuery, newUser);
    ' Define a new user 
    Dim newUser = New User With {
    	.Name = "John Doe",
    	.Email = "john@example.com"
    }
    
    ' SQL query/stored procedure to insert a new user
    Dim insertQuery As String = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)"
    
    ' Execute the query
    connection.Execute(insertQuery, newUser)
    $vbLabelText   $csharpLabel

IronPDFの紹介

IronPDF is a C# library from Iron Softwareが開発したC#ライブラリであり、開発者が.NETアプリケーション内でPDFドキュメントをプログラム的に作成、編集、操作することを可能にします。 HTMLや画像、その他のフォーマットからPDFドキュメントを生成したり、既存のPDFファイルにテキストや画像、さまざまな要素を追加するような機能を提供します。 IronPDFは、.NET開発者向けにPDF生成と操作タスクを簡素化することを目的としており、包括的なツールとAPIを提供します。

IronPDFは.NETアプリケーション内でのPDF生成と操作のための機能を多様に提供します:

  1. HTMLからPDFへの変換: CSSスタイルを含むHTMLコンテンツをPDFドキュメントに変換します。
  2. 画像からPDFへの変換: 画像(JPEG、PNG、BMPなど)をPDFドキュメントに変換します。
  3. テキストからPDFへの変換: プレーンテキストまたはフォーマットされたテキスト(RTF)をPDFドキュメントに変換します。
  4. PDF生成: プログラム的に最初からPDFドキュメントを作成します。
  5. PDF編集: テキスト、画像、その他の要素を追加または変更して既存のPDFドキュメントを編集します。
  6. PDFの結合と分割: 複数のPDFドキュメントを1つのドキュメントに結合するか、1つのPDFドキュメントを複数のファイルに分割します。
  7. PDFセキュリティ: パスワード保護や暗号化を適用してPDFドキュメントへのアクセスを制限し、機密情報を保護します。
  8. PDFフォームの自動入力: プログラム的にデータを使用してPDFフォームを自動入力します。
  9. PDF印刷: .NETアプリケーションから直接PDFドキュメントを印刷します。
  10. PDF変換設定: PDF生成中にページサイズ、向き、余白、圧縮などの多様な設定をカスタマイズします。
  11. PDFテキスト抽出: PDFドキュメントからテキストコンテンツを抽出して、さらに処理や分析を行います。
  12. PDFメタデータ: PDFドキュメントのメタデータ(著者、タイトル、主題、キーワードなど)を設定します。

IronPDFとDapperを使用してPDFドキュメントを生成する

Visual Studioでコンソールアプリケーションを作成する

Dapper C#(開発者向けの仕組み): 図1 - Visual Studioでコンソールアプリケーションを作成する

プロジェクト名と場所を指定する

Dapper C#(開発者向けの仕組み): 図2 - プロジェクトの名付け

.NETバージョンを選択する

Dapper C#(開発者向けの仕組み): 図3 - 望む.NETバージョンを選択する

以下のパッケージをVisual Studioのパッケージマネージャまたはコンソールからインストールする

dotnet add package Microsoft.Data.Sqlite
dotnet add package Microsoft.Data.Sqlite
SHELL

Dapper C#(開発者向けの仕組み): 図4 - Visual StudioパッケージマネージャからMicrosoft Data Sqliteをインストールする

dotnet add package Dapper --version 2.1.35
dotnet add package Dapper --version 2.1.35
SHELL

Dapper C#(開発者向けの仕組み): 図5 - DapperをVisual Studioパッケージマネージャからインストールする

dotnet add package IronPdf --version 2024.4.2
dotnet add package IronPdf --version 2024.4.2
SHELL

Dapper C#(開発者向けの仕組み): 図6 - Visual StudioパッケージマネージャからIronPDFをインストールする

以下のコードを使用してPDFドキュメントを生成する:

using Dapper; // Import Dapper for ORM functionalities
using IronPdf; // Import IronPDF for PDF generation
using Microsoft.Data.Sqlite; // Import Sqlite for database connection

// Define the connection string for SQLite database
string connectionString = "Data Source=ironPdf.db";

// Create a string to hold the content for the PDF document
var content = "<h1>Demonstrate IronPDF with Dapper</h1>";

// Add HTML content
content += "<h2>Create a new database using Microsoft.Data.Sqlite</h2>";
content += "<p>new SqliteConnection(connectionString) and connection.Open()</p>";

// Open the database connection
using (var connection = new SqliteConnection(connectionString))
{
    connection.Open();

    // Create a Users Table using Dapper
    content += "<h2>Create a Users Table using Dapper and SQL insert query</h2>";
    content += "<p>CREATE TABLE IF NOT EXISTS Users</p>";

    // SQL statement to create a Users table
    string sql = "CREATE TABLE IF NOT EXISTS Users (\n    Id INTEGER PRIMARY KEY,\n    Name TEXT,\n    Email TEXT\n);";
    connection.Execute(sql);

    // Add Users to table using Dapper
    content += "<h2>Add Users to table using Dapper</h2>";
    content += AddUser(connection, new User { Name = "John Doe", Email = "john@example.com" });
    content += AddUser(connection, new User { Name = "Smith William", Email = "Smith@example.com" });
    content += AddUser(connection, new User { Name = "Rock Bill", Email = "Rock@example.com" });
    content += AddUser(connection, new User { Name = "Jack Sparrow", Email = "Jack@example.com" });
    content += AddUser(connection, new User { Name = "Tomus Tibe", Email = "Tomus@example.com" });

    // Retrieve and display users from database
    content += "<h2>Get Users From table using Dapper</h2>";
    string query = "SELECT * FROM Users";
    var users = connection.Query<User>(query).ToList();

    // Display each user detail retrieved from the database
    foreach (var user in users)
    {
        content += $"<p>Id:{user.Id}, Name:{user.Name}, email: {user.Email}</p>";
        Console.WriteLine($"{user.Id}. User Name:{user.Name}, Email:{user.Email}");
    }

    // Create PDF from the accumulated HTML content
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(content);

    // Save the PDF to a file
    pdf.SaveAs("dapper.pdf");
}

// Method to add user to the database and accumulate HTML content
string AddUser(SqliteConnection sqliteConnection, User user)
{
    string insertQuery = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
    sqliteConnection.Execute(insertQuery, user);
    return $"<p>Name:{user.Name}, email: {user.Email}</p>"; 
}
using Dapper; // Import Dapper for ORM functionalities
using IronPdf; // Import IronPDF for PDF generation
using Microsoft.Data.Sqlite; // Import Sqlite for database connection

// Define the connection string for SQLite database
string connectionString = "Data Source=ironPdf.db";

// Create a string to hold the content for the PDF document
var content = "<h1>Demonstrate IronPDF with Dapper</h1>";

// Add HTML content
content += "<h2>Create a new database using Microsoft.Data.Sqlite</h2>";
content += "<p>new SqliteConnection(connectionString) and connection.Open()</p>";

// Open the database connection
using (var connection = new SqliteConnection(connectionString))
{
    connection.Open();

    // Create a Users Table using Dapper
    content += "<h2>Create a Users Table using Dapper and SQL insert query</h2>";
    content += "<p>CREATE TABLE IF NOT EXISTS Users</p>";

    // SQL statement to create a Users table
    string sql = "CREATE TABLE IF NOT EXISTS Users (\n    Id INTEGER PRIMARY KEY,\n    Name TEXT,\n    Email TEXT\n);";
    connection.Execute(sql);

    // Add Users to table using Dapper
    content += "<h2>Add Users to table using Dapper</h2>";
    content += AddUser(connection, new User { Name = "John Doe", Email = "john@example.com" });
    content += AddUser(connection, new User { Name = "Smith William", Email = "Smith@example.com" });
    content += AddUser(connection, new User { Name = "Rock Bill", Email = "Rock@example.com" });
    content += AddUser(connection, new User { Name = "Jack Sparrow", Email = "Jack@example.com" });
    content += AddUser(connection, new User { Name = "Tomus Tibe", Email = "Tomus@example.com" });

    // Retrieve and display users from database
    content += "<h2>Get Users From table using Dapper</h2>";
    string query = "SELECT * FROM Users";
    var users = connection.Query<User>(query).ToList();

    // Display each user detail retrieved from the database
    foreach (var user in users)
    {
        content += $"<p>Id:{user.Id}, Name:{user.Name}, email: {user.Email}</p>";
        Console.WriteLine($"{user.Id}. User Name:{user.Name}, Email:{user.Email}");
    }

    // Create PDF from the accumulated HTML content
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(content);

    // Save the PDF to a file
    pdf.SaveAs("dapper.pdf");
}

// Method to add user to the database and accumulate HTML content
string AddUser(SqliteConnection sqliteConnection, User user)
{
    string insertQuery = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
    sqliteConnection.Execute(insertQuery, user);
    return $"<p>Name:{user.Name}, email: {user.Email}</p>"; 
}
Imports Microsoft.VisualBasic
Imports Dapper ' Import Dapper for ORM functionalities
Imports IronPdf ' Import IronPDF for PDF generation
Imports Microsoft.Data.Sqlite ' Import Sqlite for database connection

' Define the connection string for SQLite database
Private connectionString As String = "Data Source=ironPdf.db"

' Create a string to hold the content for the PDF document
Private content = "<h1>Demonstrate IronPDF with Dapper</h1>"

' Add HTML content
Private content &= "<h2>Create a new database using Microsoft.Data.Sqlite</h2>"
Private content &= "<p>new SqliteConnection(connectionString) and connection.Open()</p>"

' Open the database connection
Using connection = New SqliteConnection(connectionString)
	connection.Open()

	' Create a Users Table using Dapper
	content &= "<h2>Create a Users Table using Dapper and SQL insert query</h2>"
	content &= "<p>CREATE TABLE IF NOT EXISTS Users</p>"

	' SQL statement to create a Users table
	Dim sql As String = "CREATE TABLE IF NOT EXISTS Users (" & vbLf & "    Id INTEGER PRIMARY KEY," & vbLf & "    Name TEXT," & vbLf & "    Email TEXT" & vbLf & ");"
	connection.Execute(sql)

	' Add Users to table using Dapper
	content &= "<h2>Add Users to table using Dapper</h2>"
	content += AddUser(connection, New User With {
		.Name = "John Doe",
		.Email = "john@example.com"
	})
	content += AddUser(connection, New User With {
		.Name = "Smith William",
		.Email = "Smith@example.com"
	})
	content += AddUser(connection, New User With {
		.Name = "Rock Bill",
		.Email = "Rock@example.com"
	})
	content += AddUser(connection, New User With {
		.Name = "Jack Sparrow",
		.Email = "Jack@example.com"
	})
	content += AddUser(connection, New User With {
		.Name = "Tomus Tibe",
		.Email = "Tomus@example.com"
	})

	' Retrieve and display users from database
	content &= "<h2>Get Users From table using Dapper</h2>"
	Dim query As String = "SELECT * FROM Users"
	Dim users = connection.Query(Of User)(query).ToList()

	' Display each user detail retrieved from the database
	For Each user In users
		content += $"<p>Id:{user.Id}, Name:{user.Name}, email: {user.Email}</p>"
		Console.WriteLine($"{user.Id}. User Name:{user.Name}, Email:{user.Email}")
	Next user

	' Create PDF from the accumulated HTML content
	Dim renderer = New ChromePdfRenderer()
	Dim pdf = renderer.RenderHtmlAsPdf(content)

	' Save the PDF to a file
	pdf.SaveAs("dapper.pdf")
End Using

' Method to add user to the database and accumulate HTML content
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'string AddUser(SqliteConnection sqliteConnection, User user)
'{
'	string insertQuery = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
'	sqliteConnection.Execute(insertQuery, user);
'	Return string.Format("<p>Name:{0}, email: {1}</p>", user.Name, user.Email);
'}
$vbLabelText   $csharpLabel

コードの説明

  1. PDF生成用のコンテンツホルダーとして文字列を作成します。
  2. Microsoft.Data.Sqliteを使用して新しいデータベースを作成し、connection.Open()で空のデータベースを作成します。
  3. Dapperを使用してUsersテーブルを作成し、挿入のためのSQLクエリを実行します。
  4. Dapperを使用して挿入クエリを使用して表にユーザーを追加します。
  5. データベースから全てのユーザーを選択するクエリを実行します。
  6. IronPDFが提供するChromePdfRendererSaveAsメソッドを使用して生成されたコンテンツをPDFとして保存します。

出力

Dapper C#(開発者向けの仕組み): 図7 - 上記のパッケージすべてを利用したPDF出力例

ライセンス(IronPDFのトライアル利用可能)

IronPDFのライセンス情報は、プロジェクト内でのコンプライアンスと使用を確保するために入手可能です。

開発者用のトライアルライセンスはIronPDFトライアルライセンスページを通じて取得できます。

以下に示したappSettings.jsonファイルのキーを置き換えてください:

{
  "IronPdf.License.LicenseKey" : "The Key Goes Here"
}

結論

Dapperは.NETアプリケーションにおけるデータアクセスを簡素化し、SQLiteと組み合わせることでデータベース管理のための軽量で効率的なソリューションを提供します。 この記事で示したステップを追うことで、Dapperを利用してSQLiteデータベースとシームレスにやり取りし、頑丈で拡張可能なアプリケーションを簡単に構築できます。 IronPDFと共に、開発者はDapperのようなORMデータベースやIronPDFのようなPDF生成ライブラリに関連するスキルを習得できます。

よくある質問

C# における Dapper とは?

Dapper は .NET プラットフォーム向けのオブジェクトリレーショナルマッピング (ORM) フレームワークで、その速度と性能で知られています。開発者がオブジェクト指向のドメインモデルを従来のリレーショナルデータベースにマッピングすることを可能にします。

Dapper はデータベース操作のパフォーマンスをどのように向上させるのですか?

Dapper は軽量で効率的にオブジェクトをマッピングすることにより、パフォーマンスを向上させます。生の ADO.NET データリーダーの速度に匹敵し、SQL データベースをクエリするための便利な拡張メソッドで IDbConnection インターフェースを強化します。

Dapper で非同期データアクセスをどのように行うことができますか?

Dapper は QueryAsyncQueryFirstOrDefaultAsyncExecuteAsync などの非同期拡張メソッドを提供し、I/O 依存の操作に最適なデータベースクエリを非同期に実行することを開発者に可能にします。

PDF 生成を .NET アプリケーションにどのように統合しますか?

IronPDF を使用して、.NET アプリケーションに PDF 生成を統合できます。プログラム的に PDF 文書を作成、編集、操作することができ、HTML や画像、テキストを PDF に変換し、既存の PDF を編集することができます。

SQLite と Dapper を使用するための環境をどのようにセットアップしますか?

環境をセットアップするには、Visual Studio または Visual Studio Code、.NET SDK、および .NET 用 SQLite パッケージが必要です。これらのパッケージは dotnet CLI を使用してインストールできます。

データベースクエリ結果から PDF レポートをどのように生成しますか?

最初に Dapper でデータを取得し、その後 IronPDF の機能を使用して出力を PDF としてフォーマットすることにより、IronPDF を使用してデータベースクエリ結果から PDF レポートを生成します。

Dapper を使って C# で SQLite データベースをどのように作成およびクエリしますか?

SqliteConnection で接続を確立し、Dapper の Execute メソッドを使用して SQL クエリを実行することにより SQLite データベースを作成します。データベースを効率的にクエリするために Dapper の Query メソッドを使用できます。

Dapper は複雑なデータ関係を処理できますか?

はい、Dapper は単一対多および多対多の関係をそのマルチマッピング機能を使用して処理でき、複雑なデータの取得を簡素化します。

.NET で PDF 生成ライブラリを使用することの利点は何ですか?

IronPDF のような PDF 生成ライブラリは、シームレスな PDF 生成と操作を可能にすることで .NET アプリケーションを強化し、HTML から PDF への変換、PDF の編集、マージ、分割、セキュリティ機能などを提供します。

IronPDF の試用版ライセンスをどのように取得しますか?

IronPDF の試用版ライセンスは IronPDF の試用版ライセンスページから取得できます。取得したライセンスキーをプロジェクトの設定に含める必要があります。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。