首页 程序笔记 .NET轻量级ORM框架Dapper.NET高级应用示例

.NET轻量级ORM框架Dapper.NET高级应用示例

Dapper是一个轻量级的ORM(对象关系映射)库,用于.NET应用程序与数据库之间的数据访问。它允许你使用SQL查询来执行数据库操作,而不需要复杂的映射配置。在这篇文章中,我将为您提供Dapper的高级应用功能示例,每个示例都有源代码和注释。这些示例将涵盖Dapper的一些高级功能,以帮助你更好地理解如何在实际应用中使用它。

示例1:多表关联查询

Dapper允许你轻松执行多表关联查询。在这个示例中,我们将查询两个表,一个是Customers表,另一个是Orders表,并将它们关联起来。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public decimal TotalAmount { get; set; }
}

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string query = "SELECT c.CustomerId, c.CustomerName, o.OrderId, o.TotalAmount " +
                       "FROM Customers c " +
                       "JOIN Orders o ON c.CustomerId = o.CustomerId";

        var result = dbConnection.Query<Customer, Order, Customer>(
            query,
            (customer, order) =>
            {
                customer.Orders = order;
                return customer;
            },
            splitOn: "OrderId"
        );

        foreach (var customer in result)
        {
            Console.WriteLine($"Customer ID: {customer.CustomerId}, Name: {customer.CustomerName}");
            Console.WriteLine($"Order ID: {customer.Orders.OrderId}, Total Amount: {customer.Orders.TotalAmount}");
            Console.WriteLine();
        }
    }
}

示例2:事务处理

Dapper允许你使用事务来确保一组操作要么全部成功,要么全部失败。在这个示例中,我们将演示如何在Dapper中使用事务。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();

        using var transaction = dbConnection.BeginTransaction();

        try
        {
            string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";
            string updateQuery = "UPDATE Customers SET CustomerName = @CustomerName WHERE CustomerId = @CustomerId";

            var product = new { Name = "ProductX", Price = 19.99 };
            var customer = new { CustomerName = "NewName", CustomerId = 1 };

            dbConnection.Execute(insertQuery, product, transaction: transaction);
            dbConnection.Execute(updateQuery, customer, transaction: transaction);

            // Commit the transaction if all operations are successful
            transaction.Commit();
            Console.WriteLine("Transaction committed.");
        }
        catch (Exception ex)
        {
            // Rollback the transaction if any operation fails
            transaction.Rollback();
            Console.WriteLine("Transaction rolled back. Error: " + ex.Message);
        }
    }
}

示例3:自定义类型映射

Dapper允许你自定义数据类型到.NET类型的映射。在这个示例中,我们将使用TypeHandler来自定义Point类型的映射。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;
using Npgsql;
using NpgsqlTypes;

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }
}

public class PointTypeHandler : SqlMapper.TypeHandler<Point>
{
    public override void SetValue(IDbDataParameter parameter, Point value)
    {
        parameter.Value = $"({value.X},{value.Y})";
        parameter.DbType = DbType.String;
    }

    public override Point Parse(object value)
    {
        if (value is string strValue)
        {
            var parts = strValue.Trim('(', ')').Split(',');
            if (parts.Length == 2 && double.TryParse(parts[0], out double x) && double.TryParse(parts[1], out double y))
            {
                return new Point { X = x, Y = y };
            }
        }
        return null;
    }
}

class Program
{
    static void Main()
    {
        SqlMapper.AddTypeHandler(new PointTypeHandler());

        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new NpgsqlConnection(connectionString);

        string query = "SELECT PointColumn FROM MyTable WHERE Id = @Id";
        var result = dbConnection.Query<Point>(query, new { Id = 1 }).FirstOrDefault();

        if (result != null)
        {
            Console.WriteLine($"X: {result.X}, Y: {result.Y}");
        }
        else
        {
            Console.WriteLine("Point not found.");
        }
    }
}

示例4:批量插入

Dapper支持批量插入数据,这对于大规模数据操作非常有用。在这个示例中,我们将演示如何批量插入多个产品记录。

using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();

        var products = new List<Product>
        {
            new Product { Name = "ProductA", Price = 10.99m },
            new Product { Name = "ProductB", Price = 15.99m },
            new Product { Name = "ProductC", Price = 20.99m }
        };

        string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";
        int rowsAffected = dbConnection.Execute(insertQuery, products);

        Console.WriteLine($"{rowsAffected} rows inserted.");
    }
}

示例5:自定义SQL语句

虽然Dapper通常用于执行SQL查询,但你也可以执行自定义的SQL语句,例如存储过程或函数调用。在这个示例中,我们将演示如何执行一个存储过程。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
   

 {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string storedProcedure = "MyStoredProcedure";
        var parameters = new DynamicParameters();
        parameters.Add("Param1", 123);
        parameters.Add("Param2", "TestValue", DbType.String, ParameterDirection.Input, 50);

        var result = dbConnection.Query<int>(storedProcedure, parameters, commandType: CommandType.StoredProcedure).FirstOrDefault();

        Console.WriteLine($"Stored procedure result: {result}");
    }
}

示例6:自定义SQL语句执行

你可以使用Dapper的Execute方法来执行自定义的SQL语句,而不仅仅是查询。在这个示例中,我们将演示如何执行一个自定义的更新语句。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string updateStatement = "UPDATE Customers SET CustomerName = @NewName WHERE CustomerId = @CustomerId";
        var parameters = new { NewName = "NewName", CustomerId = 1 };

        int rowsAffected = dbConnection.Execute(updateStatement, parameters);

        Console.WriteLine($"{rowsAffected} rows updated.");
    }
}

示例7:异步查询

Dapper支持异步查询,这对于高并发应用程序非常有用。在这个示例中,我们将演示如何使用异步方法执行查询。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string query = "SELECT * FROM Products";
        var products = await dbConnection.QueryAsync<Product>(query);

        foreach (var product in products)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }
    }
}

示例8:自定义表名

你可以使用Dapper的Table特性来指定实体类与数据库中不同表之间的映射关系。在这个示例中,我们将演示如何自定义表名。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

[Table("MyCustomTableName")]
public class CustomTable
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string query = "SELECT * FROM MyCustomTableName";
        var result = dbConnection.Query<CustomTable>(query);

        foreach (var item in result)
        {
            Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
        }
    }
}

示例9:自定义参数前缀

Dapper默认使用@作为参数前缀,但你可以自定义参数前缀。在这个示例中,我们将演示如何自定义参数前缀为$。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        SqlMapperExtensions.Configure("$$$"); // 设置参数前缀为 $$$

        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        string query = "SELECT * FROM Products WHERE Name = $$$productName";
        var result = dbConnection.Query<Product>(query, new { productName = "ProductA" });

        foreach (var product in result)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }
    }
}

示例10:查询分页

Dapper使分页查询变得容易,你可以使用LIMIT和OFFSET来执行分页查询。在这个示例中,我们将演示如何执行分页查询。

using Dapper;
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using IDbConnection dbConnection = new SqlConnection(connectionString);

        int pageSize = 10;
        int pageNumber = 2;

        string query = "SELECT * FROM Products ORDER BY ProductId OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY";
        var result = dbConnection.Query<Product>(query, new { Offset = (pageNumber - 1) * pageSize, PageSize = pageSize });

        foreach (var product in result)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }
    }
}

这些示例演示了Dapper的一些高级功能,包括多表关联查询、事务处理、自定义类型映射、批量插入、自定义SQL语句、异步查询、自定义表名、自定义参数前缀和查询分页。通过这些示例,你可以更好地了解如何在实际应用中充分利用Dapper来简化数据访问任务。

3

声明 本站内容部分来源于网络,仅供参考学习交流并不代表本站观念,如无意中侵犯您的权益( 包括/图片/视频/个人隐私等信息 )请来信告知,本站收到信息会尽快处理并回访,联系邮箱:laodilailiao@foxmail.com

站心网

Dapper是一个轻量级的ORM(对象关系映射)库,用于.NET应用程序与数据库之间的数据访问。它允许你使用SQL查..

为您推荐

EasyCaching:一款灵活高效的 .NET 缓存库

EasyCaching 项目简介EasyCaching 是一个开源的 .NET 缓存抽象库,由 DotNetCore 团队开发,旨在为 .NET 应用提供简单、统一、强大且可扩展的缓存解决方案。它支持内存缓存(In-Memory)、Redis、Memcached、LiteDB..

.NET 依赖注入如何一个接口注册两种实现

在.NET的依赖注入(Dependency Injection,DI)系统中,一个接口注册两种或多种实现是常见的需求,尤其是在需要根据不同场景或条件选择不同实现时。以下是一些实现方法:1. 使用 IEnumerable<T> 解析所有实现这是最..

.NET C# 过滤从富文本编辑器html里的Javascript脚本

富文本编辑器在允许用户输入丰富内容的同时,也带来了跨站脚本攻击(XSS)的风险。过滤提交的 HTML 中的 <script> 脚本是防止跨站脚本攻击(XSS)的关键步骤。在 .NET C# 服务端过滤 <script> 脚本主要有以下几种方..

ZLinq:.NET 高性能 LINQ 替代方案及其使用指南

在 .NET 开发中,LINQ(Language Integrated Query)为数据查询提供了简洁且强大的语法。然而,传统的 LINQ 在处理大量数据时可能会引发性能瓶颈,主要由于频繁的内存分配和对象创建。为解决这一问题,Cysharp 团队..

.NET使用AutoMapper简化对象映射

在.NET软件开发中,常常需要将一个对象的数据转换并映射到另一个对象上。​这种手动映射的过程既繁琐又容易出错,影响开发效率和代码可维护性。​为了解决这一问题,AutoMapper应运而生。​什么是 AutoMapper?AutoM..

.NET C# RESTful API交互Refit库使用教程

Refit 是一个 .NET C# 库,它简化了与 RESTful API 的交互。Refit 受到 Square 的 Retrofit 库的启发,它将 REST API 转换为实时接口,允许你以声明方式定义 REST API 调用。Refit 的特点1. 声明式 API 定义:Refit ..

.NET C# System.Text.Json进阶使用技巧

System.Text.Json 是 .NET 中用于处理 JSON 数据的强大库。除了基本用法外,它还提供了许多进阶技巧,可以帮助你更高效、更灵活地处理 JSON 数据。以下是一些 System.Text.Json 的进阶使用技巧:1. 自定义序列化和反..

.NET Core 使用ML.NET 机器学习分析预测股票走势

在 .NET Core 中,你可以利用 ML.NET 框架来构建机器学习模型,以预测股票价格走势。以下是一个基本的实现步骤:​1. 准备数据:​收集并整理股票的历史数据,包括日期、开盘价、最高价、最低价、收盘价和成交量等信..

.NET 日志库 Serilog 使用教程

1. Serilog 简介Serilog 是 .NET 生态中强大且灵活的日志库,支持结构化日志记录,并提供多种日志接收器(Sinks),可以将日志输出到控制台、文件、数据库等不同存储介质。Serilog 适用于控制台应用、ASP.NET Core ..

值得探索的 8 个机器学习 JavaScript 框架

JavaScript开发人员倾向于寻找可用于机器学习模型训练的JavaScript框架。下面是一些机器学习算法,基于这些算法可以使用本文中列出的不同JavaScript框架来模型训练:简单的线性回归多变量线性回归逻辑回归朴素贝叶斯..

以我的亲身经历为例,告诉大家写简历和面试的技巧(面向高级开发和架构师)

之前我也写过不少介绍面试相关的博文,有些文章的点击量还不低,这些面试相关的经验大多都是从我面试别人的过程中提炼出来了。在18年底到19年3月,陆续面试了几家公司,有成有不成的,最终进了一家比较满意的知名外..

.NET C# 单元测试 mock File.Exists的返回值

在 .NET 单元测试中,使用 Moq 来模拟 File.Exists 方法的返回值,可以这样做:1. 使用 Mock<FileSystem>(推荐).NET 提供了 System.IO.Abstractions 库,你可以使用 Mock<IFileSystem> 来替代 File,这样更符合依..

.NET Core 适配 鸿蒙HarmonyOS 的最新进展

.NET Core适配鸿蒙HarmonyOS的最新进展:运行能力方面目前.Net完全具备可以在OpenHarmony系统上运行的能力。其中,NativeAOT方式是较为可行的一种,它编译出的原生so不依赖glibc,可与鸿蒙系统的libc兼容,能在鸿蒙..

VS创建.NET Core项目使用Docker方式部署到Linux服务器

在 Visual Studio(VS) 中,使用 Docker 方式部署 .NET Core 项目 到 Linux 服务器,可以简化环境管理并提高部署效率。以下是完整教程:1. 在 VS 创建 .NET Core 项目并启用 Docker新建 ASP.NET Core 项目打开 Visu..

.NET C#查询全球IP地址信息 IPTools库 使用教程

IPTools 是一个用于快速查询全球 IP 地址信息的库,支持国内和国际 IP 查询,提供详细的地理位置信息(如国家、省份、城市)以及经纬度等数据。IPTools GitHub地址:https://github.com/stulzq/IPToolsIPTools.China..

2025年.NET 10 和 C# 13 新特性示例

.NET 10预计将于2025年11月正式发布,带来一系列性能优化、开发者效率提升和跨平台能力增强。尽管官方功能集仍在开发中,早期预览版与社区讨论已揭示了多项值得期待的改进。这些增强将基于.NET 9的基础,引入新语言..

.NET Core网站减少内存占用的方法

在.NET Core网站开发中,有效管理内存占用对于保证应用程序的性能和稳定性至关重要。以下是一些减少内存占用的关键策略,它们着重于代码优化、内存管理以及相关因素的综合考虑。代码层面的优化首先,编写高效的代码..

.NET平台QR二维码生成库Net.Codecrete.QrCodeGenerator使用教程

今天给大家介绍一个免费的二维码生成库 Net.Codecrete.QrCodeGenerator ,它非常简洁、易用,且可以生成符合二维码标准的二维码图像。Net.Codecrete.QrCodeGenerator是一个开源的二维码生成库,适用于.NET平台。它基..

.NET9 SDK 新版本引入了新的解决方案文件格式.slnx

微软发布了 .NET 9 SDK 的新版本, 在这个新版本中引入了新的解决方案文件格式 slnx 的支持, 现在可以从 dotnet cli 来创建和维护 slnx 了, 并且支持了从 sln 迁移到 slnx, 目前 VisualStudio 和 Rider 都已经支持了 ..

.NET10 C#13最新语法糖用法示例

.NET 10 与 C# 13 带来了更高效的语法和更灵活的类型支持,包括 params 集合扩展、新的 \e 转义序列、方法组的自然类型推断优化,以及 ref struct 允许实现接口等特性,进一步提升了开发体验和代码可读性。C# 13 引..

发表回复

返回顶部