跳過到頁腳內容
.NET幫助

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

在現代軟體開發中,有效地存取資料庫是應用程式效能和可擴展性的關鍵。 Dapper,一款針對.NET的輕量級物件關聯映射(ORM),提供了一個簡化的資料庫交互方式。 在本文中,我們將探索如何使用Dapper C#與SQLite資料庫檔案,並透過程式碼範例展示其簡單性和有效性。 此外,我將介紹名為IronPDF的卓越PDF生成程式庫,來自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資料庫檔案,其中有一個包含"Id"、"Name"和"Email"欄位的"Users"表。

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;
$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
    }
    $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}");
    }
    $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);
    $vbLabelText   $csharpLabel

介紹IronPDF

IronPDF是由Iron Software開發的C#程式庫,允許開發者在.NET應用程式中以程式方式創建、編輯和操作PDF文件。 它提供了從HTML、圖像和其他格式生成PDF文件的功能,並向現有的PDF文件添加文本、圖像和各種元素。 IronPDF旨在為.NET開發者簡化PDF生成和操作任務,提供了全面的工具和API。

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>"; 
}
$vbLabelText   $csharpLabel

程式碼說明

  1. 首先創建一個字串內容持有者,用於PDF生成。
  2. 使用connection.Open()將創建一個空數據庫。
  3. 使用Dapper創建Users表併通過執行SQL查詢插入資料。
  4. 使用Dapper插入查詢將用戶添加到表中。
  5. 查詢以選擇資料庫中的所有用戶。
  6. 使用IronPDF提供的SaveAs方法將生成的內容儲存為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 首先通過 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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me