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
);结合 SQLite 使用 Dapper
- 首先,确保您已导入必要的命名空间:
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 中创建一个控制台应用程序

提供项目名称和位置

选择 .NET 版本

从 Visual Studio 包管理器或控制台安装以下包
dotnet add package Microsoft.Data.Sqlitedotnet add package Microsoft.Data.Sqlite
dotnet add package Dapper --version 2.1.35dotnet add package Dapper --version 2.1.35
dotnet add package IronPdf --version 2024.4.2dotnet add package IronPdf --version 2024.4.2
使用下面的代码生成 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 文件中的密钥:
{
"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 提供异步扩展方法,比如 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。
如何在 C# 中使用 Dapper 创建和查询 SQLite 数据库?
通过建立与 SqliteConnection 的连接并使用 Dapper 的 Execute 方法执行 SQL 查询来创建 SQLite 数据库。您可以使用 Dapper 的 Query 方法查询数据库以高效检索数据。
Dapper 可以处理复杂的数据关系吗?
可以,Dapper 可以通过其多重映射功能处理一对多和多对多关系,从而简化复杂的数据检索。
在 .NET 中使用 PDF 生成库有哪些优点?
像 IronPDF 这样的 PDF 生成库通过支持无缝的 PDF 生成和操作来增强 .NET 应用程序,提供 HTML 到 PDF 转换、PDF 编辑、合并、拆分及安全功能等。
如何获取 IronPDF 的试用许可证?
可以通过 IronPDF 试用许可证页面获取试用许可证。需要在您的项目配置中包含许可证密钥。








