跳過到頁腳內容
.NET幫助

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

在現代軟體開發中,有效率地存取資料庫對應用程式的效能與擴充性至關重要。 Dapper 是適用於 .NET 的輕量級物件-關聯映射器 (ORM),提供簡化的資料庫互動方式。 在本文中,我們將探討如何在 SQLite 資料庫檔案中使用 Dapper C#,並透過程式碼範例展示其簡易性與有效性。 此外,我還會介紹 Iron Software 所提供、名為 IronPDF 的非凡 PDF 產生函式庫。

什麼是 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。

  1. .NET SDK。 3.適用於 .NET 的 SQLite 套件。

若要安裝 SQLite 套件,請在專案目錄中執行下列指令:

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

建立 SQLite 資料庫:為了示範的目的,讓我們建立一個簡單的 SQLite 資料庫檔案,檔案名稱為 "example.db",其中的 "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

2.建立與 SQLite 資料庫的連線:

```csharp
string connectionString = "Data Source=example.db"; // SQLite database connection string
using (var connection = new SqliteConnection(connectionString))
{
    connection.Open();
    // Your Dapper queries will go here
}
```

3.使用 Dapper 執行查詢:

```csharp
// 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}");
}
```

4.使用 Dapper 將資料插入資料庫:

```csharp
// 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);
```

介紹 IronPDF。

IronPDF 是來自 Iron Software 的 C# 函式庫,可讓開發人員在 .NET 應用程式中以程式化的方式建立、編輯和處理 PDF 文件。 它提供的功能包括從 HTML、影像和其他格式產生 PDF 文件,以及在現有 PDF 文件中加入文字、影像和各種元素。 IronPDF 旨在為 .NET 開發人員提供一套全面的工具和 API,從而簡化 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# (How It Works For Developers):圖 1 - 在 Visual Studio 中建立控制台應用程式

提供專案名稱和地點

Dapper C# (How It Works For Developers):圖 2 - 命名專案

選擇 .NET 版本

Dapper C# (How It Works For Developers):圖 3 - 選擇所需的 .NET 版本

從 Visual Studio 套件管理員或主控台安裝下列套件

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

Dapper C# (How It Works For Developers):圖 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# (How It Works For Developers):圖 5 - 從 Visual Studio 套件管理員安裝 Dapper

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

Dapper C# (How It Works For Developers):圖 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 生成的字串內容持有人開始。

  1. 使用 Microsoft.Data.Sqlite 建立一個新資料庫,connection.Open() 將會建立一個空資料庫。
  2. 使用 Dapper 建立 Users 表,並執行 SQL 查詢進行插入。 4.使用 Dapper 透過插入查詢將使用者新增至資料表。 5.從資料庫中選擇所有使用者的查詢。
  3. 使用 IronPDF 提供的 ChromePdfRendererSaveAs 方法將產生的內容儲存為 PDF。

輸出

Dapper C# (How It Works For Developers):圖 7 - 利用以上安裝的所有套件輸出 PDF 的範例

授權 (IronPDF 提供試用版)。

IronPDF 的 許可資訊可供使用,以確保您的專案符合規定並使用。

開發人員可透過 IronPDF試用授權頁面取得試用授權。

請替換下方 appSettings.json 檔案中的金鑰:

{
  "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 的試用許可證。需要在你的項目配置中包含該許可證密鑰。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我