跳過到頁腳內容
.NET幫助

Dapper C#(對於開發者的運行原理)

在現代軟件開發中,有效訪問資料庫對於應用程式的性能和可擴展性至關重要。 Dapper 是一個針對 .NET 的輕量級物件關聯映射 (ORM),提供了一種流線型的方法來進行資料庫互動。 在本文中,我們將探討如何使用 Dapper C# 與 SQLite 資料庫檔案,並通過代碼示例展示其簡單性和有效性。 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 無縫處理一對多和多對多關係,允許高效地執行多個查詢,從而簡化複雜資料檢索。

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
);

使用 Dapper 與 SQLite

  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 通過提供全面的工具和 API,旨在簡化 .NET 開發人員的 PDF 生成和操作任務。

IronPDF 提供了一系列功能以在 .NET 應用程序中生成和操作 PDF:

  1. HTML 到 PDF 轉換: 將 HTML 內容,包括 CSS 樣式,轉換為 PDF 文件。
  2. 圖像到 PDF 轉換: 將圖像(如 JPEG,PNG,BMP)轉換為 PDF 文件。
  3. 文本到 PDF 轉換: 將純文本或格式化文本(RTF)轉換為 PDF 文件。
  4. PDF 生成: 從零開始以程式化方式創建 PDF 文件。
  5. PDF 編輯: 通過添加或修改文本、圖像和其他元素來編輯現有 PDF 文件。
  6. PDF 合併和拆分: 將多個 PDF 文件合併為單一文件,或將 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 - 從 Visual Studio 套件管理器安裝 Dapper

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 文件中的 Key:

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

結論

Dapper 簡化了 .NET 應用程序中的數據訪問,當與 SQLite 結合使用時,它提供了一種輕量級且高效的資料管理解決方案。 通過遵循本文中概述的步驟,您可以利用 Dapper 無縫地與 SQLite 資料庫互動,使您能夠輕鬆構建穩健且可擴展的應用程序。 與 IronPDF 一起,開發人員可以獲得有關 ORM 資料庫(如 Dapper)和 PDF 生成庫(如 IronPDF)的技能。

常見問題解答

什麼是 C# 中的 Dapper?

Dapper 是一個用於 .NET 平台的物件關係映射 (ORM) 框架,以其速度和性能著稱。它允許開發人員將物件導向的領域模型映射到傳統的關係數據庫中。

Dapper 如何提高資料庫操作的性能?

Dapper 通過輕量級和高效的物件映射來提高性能。它的速度匹配原生 ADO.NET 的資料閱讀器,並透過有用的擴展方法增強了 IDbConnection 介面來查詢 SQL 資料庫。

如何使用 Dapper 執行非同步數據訪問?

Dapper 提供了如 QueryAsyncQueryFirstOrDefaultAsyncExecuteAsync 這樣的非同步擴展方法,允許開發人員非同步地執行數據庫查詢,非常適合 I/O 密集型操作。

如何將 PDF 生成整合到 .NET 應用程式中?

可以使用 IronPDF 將 PDF 生成整合到 .NET 應用程式中。它允許以程式碼方式創建、編輯和操控 PDF 文件,包括將 HTML、圖片和文字轉換成 PDF,並編輯現有的 PDF。

如何設置使用 Dapper 和 SQLite 的環境?

要設置環境,你需要 Visual Studio 或 Visual Studio Code、.NET SDK 和 .NET 的 SQLite 套件。可以使用 dotnet CLI 安裝這些套件。

如何從數據庫查詢結果生成 PDF 報告?

使用 IronPDF 首先通過 Dapper 檢索數據,然後使用 IronPDF 的功能將輸出格式化為 PDF,從數據庫查詢結果生成 PDF 報告。

如何使用 Dapper 在 C# 中創建和查詢 SQLite 數據庫?

通過 SqliteConnection 建立連接創建 SQLite 數據庫,然後使用 Dapper 的 Execute 方法執行 SQL 查詢。可以使用 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) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。