跳至页脚内容
.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
);

结合 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 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 文件中的密钥:

{
  "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 从数据库查询结果生成 PDF 报告,首先使用 Dapper 获取数据,然后使用 IronPDF 的功能将输出格式化为 PDF。

如何在 C# 中使用 Dapper 创建和查询 SQLite 数据库?

通过建立与 SqliteConnection 的连接并使用 Dapper 的 Execute 方法执行 SQL 查询来创建 SQLite 数据库。您可以使用 Dapper 的 Query 方法查询数据库以高效检索数据。

Dapper 可以处理复杂的数据关系吗?

可以,Dapper 可以通过其多重映射功能处理一对多和多对多关系,从而简化复杂的数据检索。

在 .NET 中使用 PDF 生成库有哪些优点?

像 IronPDF 这样的 PDF 生成库通过支持无缝的 PDF 生成和操作来增强 .NET 应用程序,提供 HTML 到 PDF 转换、PDF 编辑、合并、拆分及安全功能等。

如何获取 IronPDF 的试用许可证?

可以通过 IronPDF 试用许可证页面获取试用许可证。需要在您的项目配置中包含许可证密钥。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。