Dapper C#(開發者的使用方法)
在現代軟體開發中,高效存取資料庫對於應用程式的效能和可擴展性至關重要。 Dapper是適用於 .NET 的輕量級物件關聯映射器 (ORM),它提供了一種簡化的資料庫互動方法。 在本文中,我們將探討如何將 Dapper C# 與 SQLite 資料庫檔案一起使用,並透過程式碼範例展示其簡潔性和有效性。 此外,我也會介紹Iron Software公司出品的卓越的PDF生成庫IronPDF 。
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 中的關鍵非同步方法
QueryAsync:非同步執行 SQL 查詢,並將結果作為動態物件序列或強類型物件傳回。QueryFirstOrDefaultAsync:非同步執行 SQL 查詢,並傳回第一個結果;如果沒有找到結果,則傳回預設值。ExecuteAsync:非同步執行 SQL 指令(例如,INSERT、UPDATE、DELETE),並傳回受影響的行數。
環境建構:在深入學習程式碼範例之前,請確保已安裝必要的工具:
- Visual Studio 或 Visual Studio Code。
- .NET SDK。
- .NET 的 SQLite 套件。
若要安裝 SQLite 套件,請在專案目錄中執行下列命令:
dotnet add package Microsoft.Data.Sqlitedotnet add package Microsoft.Data.Sqlite建立 SQLite 資料庫:為了演示,我們建立一個名為"example.db"的簡單 SQLite 資料庫文件,其中包含一個名為"Users"的表,該表包含"Id"、"Name"和"Email"列。
CREATE TABLE Users (
Id INTEGER PRIMARY KEY,
Name TEXT,
Email TEXT
);將 Dapper 與 SQLite 結合使用
- 首先,請確保已匯入必要的命名空間:
using Microsoft.Data.Sqlite;
using Dapper;using Microsoft.Data.Sqlite;
using Dapper;建立與 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 }$vbLabelText $csharpLabel使用 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}"); }$vbLabelText $csharpLabel使用 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);$vbLabelText $csharpLabel
IronPDF簡介
IronPDF是Iron Software出品的 C# 庫,它允許開發人員在 .NET 應用程式中以程式設計方式建立、編輯和操作 PDF 文件。 它提供了從 HTML、圖像和其他格式生成 PDF 文件等功能,以及向現有 PDF 文件添加文字、圖像和各種元素的功能。 IronPDF 旨在透過提供一套全面的工具和 API,簡化 .NET 開發人員的 PDF 產生和操作任務。
IronPDF 為 .NET 應用程式中的 PDF 產生和操作提供了一系列功能:
- HTML 轉 PDF:將 HTML 內容(包括 CSS 樣式)轉換為 PDF 文件。
- 圖片轉 PDF:將圖片(如 JPEG、PNG、BMP)轉換為 PDF 文件。
- 文字轉 PDF:將純文字或格式化文字 (RTF) 轉換為 PDF 文件。
- PDF 產生:透過程式設計從頭開始建立 PDF 文件。
- PDF 編輯:透過新增或修改文字、圖像和其他元素來編輯現有的 PDF 文件。
- PDF 合併與分割:將多個 PDF 文檔合併為一個文檔,或將一個 PDF 文檔分割為多個文件。
- PDF 安全性:對 PDF 文件套用密碼保護和加密,以限制存取並保護敏感資訊。
- PDF 表單填寫:透過程式填入 PDF 表單資料。
- PDF 列印:直接從您的 .NET 應用程式列印 PDF 文件。
- PDF 轉換設定:在產生 PDF 時,可以自訂各種設置,例如頁面大小、方向、邊距、壓縮等。
- PDF 文字擷取:從 PDF 文件中擷取文字內容,以便進行進一步處理或分析。
- PDF 元資料:設定 PDF 文件的元資料(作者、標題、主題、關鍵字)。
使用 IronPDF 和 Dapper 產生 PDF 文檔
在 Visual Studio 中建立一個控制台應用程式
Dapper C#(開發者使用指南):圖 1 - 在 Visual Studio 中建立控制台應用程式
請提供項目名稱和地點
選擇 .NET 版本
Dapper C#(開發者使用指南):圖 3 - 選擇所需的 .NET 版本
請透過 Visual Studio 套件管理器或控制台安裝下列軟體套件。
dotnet add package Microsoft.Data.Sqlitedotnet add package Microsoft.Data.SqliteDapper C#(開發者使用指南):圖 4 - 從 Visual Studio 套件管理器安裝 Microsoft Data SQLite
dotnet add package Dapper --version 2.1.35dotnet add package Dapper --version 2.1.35Dapper C#(開發者使用方法):圖 5 - 從 Visual Studio 套件管理器安裝 Dapper
dotnet add package IronPdf --version 2024.4.2dotnet add package IronPdf --version 2024.4.2Dapper 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>";
}程式碼解釋
- 首先建立用於產生 PDF 的字串內容容器。
- 使用
Microsoft.Data.Sqlite建立一個新資料庫,connection.Open()將建立一個空資料庫。 - 使用 Dapper 建立
Users表並執行 SQL 查詢進行插入。 - 使用 Dapper 的插入查詢將使用者加入表中。
- 查詢資料庫中所有使用者。
- 使用 IronPDF 提供的
ChromePdfRenderer和SaveAs方法將產生的內容儲存為 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 資料讀取器相當,並透過用於查詢 SQL 資料庫的實用擴充方法增強了 IDbConnection 介面。
如何使用 Dapper 實現非同步資料存取?
Dapper 提供非同步擴充方法,如QueryAsync 、 QueryFirstOrDefaultAsync和ExecuteAsync ,允許開發人員非同步執行資料庫查詢,非常適合 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 從資料庫查詢結果產生 PDF 報告,首先使用 Dapper 檢索數據,然後使用 IronPDF 的功能將輸出格式化為 PDF。
如何使用 Dapper 在 C# 中建立和查詢 SQLite 資料庫?
使用 Dapper 的Execute方法,透過SqliteConnection建立連線並執行 SQL 查詢來建立 SQLite 資料庫。您可以使用 Dapper 的Query方法查詢資料庫,從而有效率地檢索資料。
Dapper 能否處理複雜的資料關係?
是的,Dapper 可以利用其多重映射功能來處理一對多和多對多關係,從而簡化複雜的資料檢索。
在.NET中使用PDF生成庫有哪些優勢?
像 IronPDF 這樣的 PDF 生成庫透過實現無縫的 PDF 生成和操作來增強 .NET 應用程序,提供 HTML 到 PDF 轉換、PDF 編輯、合併、分割和安全功能等功能。
如何獲得 IronPDF 的試用許可證?
您可以透過 IronPDF 試用許可證頁面取得 IronPDF 的試用許可證。許可證密鑰需要包含在您的專案配置中。







