跳至頁尾內容
開發者更新

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

在現代軟體開發中,有效地存取資料庫對應用程式的性能和可擴展性至關重要。 Dapper 是一個輕量級的物件關係映射 (ORM) 用於 .NET,提供了一種簡化的資料庫互動方法。 在本文中,我們將探討如何使用 Dapper C# 與一個 SQLite 資料庫檔案,通過程式碼範例展示其簡單性和有效性。 此外,我將介紹來自 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 or 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 是來自 Iron Software 的 C# 程式庫,允許開發者在 .NET 應用程式中以程式化方式建立、編輯和操作 PDF 文件。 它提供的功能包括從 HTML、圖片和其他格式生成 PDF 文件,以及向現有 PDF 文件中新增文字、圖片和各種元素。 IronPDF 旨在通過提供全面的工具和 APIs,簡化 .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

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資料讀取器的速度,並透過有用的擴展方法增強了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從資料庫查詢結果生成PDF報告,首先使用Dapper檢索資料,然後使用IronPDF的功能將輸出格式化為PDF。

我如何使用Dapper在C#中建立和查詢SQLite資料庫?

通過使用SqliteConnection建立連接並使用Dapper的Execute方法執行SQL查詢來建立SQLite資料庫。您可以使用Dapper的Query方法查詢資料庫以有效地檢索資料。

Dapper能夠處理複雜的資料關係嗎?

是的,Dapper可以通過其多重映射功能處理一對多和多對多關係,簡化複雜資料的檢索。

在.NET中使用PDF生成程式庫的優勢是什麼?

像IronPDF這樣的PDF生成程式庫可增強.NET應用程式的功能,提供無縫的PDF生成和操作,提供HTML到PDF轉換、PDF編輯、合併、分割和安全功能。

如何獲得IronPDF的試用授權?

可以通過IronPDF試用授權頁面獲得試用授權。授權金鑰需要包含在您的專案配置中。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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