Dapper实用教程

简介: Dapper是什么?  Dpper是一款.Net平台简单(Simple)的对象映射库,并且Dapper拥有着“微型ORM之王”的称号。就速度而言与手写ADO.NET SqlDateReader相同。ORM是Object Relational Mapper的缩写,代表着数据库与编程语言之间的映射。

Dapper是什么?

  Dpper是一款.Net平台简单(Simple)的对象映射库,并且Dapper拥有着“微型ORM之王”的称号。就速度而言与手写ADO.NET SqlDateReader相同。ORM是Object Relational Mapper的缩写,代表着数据库与编程语言之间的映射。

  Dapper的基本特性是通过扩展IDbConnection 接口,并为其提供查询数据库的方法。

Dapper是如何工作的?

  将大象装冰箱总共分三步,Dapper也是如此。

  1. 创建IDBConnection对象(例如:SqlConnection)
  2. 编写用于CRUD的Sql语句
  3. 将Sql语句当作参数纯如执行操作的方法

安装

  通过NuGet安装:https://www.nuget.org/packages/Dapper

  PM> Install-Package Dapper

方法表

  Dapper会用多个方法去扩展IDBConnection接口

  • Execute
  • Query
  • QueryFirst
  • QueryFirstOrDefault
  • QuerySingle
  • QuerySingleOrDefault
  • QueryMultiple
string sqlInvoices = "SELECT * FROM Invoice;";
string sqlInvoice = "SELECT * FROM Invoice WHERE InvoiceID = @InvoiceID;";
string sp = "EXEC Invoice_Insert";

using (var connection = My.ConnectionFactory())
{
    var invoices = connection.Query<Invoice>(sqlInvoices).ToList();
    var invoice = connection.QueryFirstOrDefault(sqlInvoice, new {InvoiceID = 1});
    var affectedRows = connection.Execute(sp, new { Param1 = "Single_Insert_1" }, commandType: CommandType.StoredProcedure);
}

参数表

  有多种不同的方式给“查询(例如:select)”和“执行(例如:delete、update、insert)”方法传递参数

  • Anonymous
  • Dynamic
  • List
  • String
// 匿名类对象(相对比较常用)
var affectedRows = connection.Execute(sql,
                    new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
                    commandType: CommandType.StoredProcedure);

// Dynamic
DynamicParameters parameter = new DynamicParameters();

parameter.Add("@Kind", InvoiceKind.WebInvoice, DbType.Int32, ParameterDirection.Input);
parameter.Add("@Code", "Many_Insert_0", DbType.String, ParameterDirection.Input);
parameter.Add("@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

connection.Execute(sql,
    new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
    commandType: CommandType.StoredProcedure);

// List
connection.Query<Invoice>(sql, new {Kind = new[] {InvoiceKind.StoreInvoice, InvoiceKind.WebInvoice}}).ToList();

// String
connection.Query<Invoice>(sql, new {Code = new DbString {Value = "Invoice_1", IsFixedLength = false, Length = 9, IsAnsi = true}}).ToList();

结果集

  查询方法的返回值可以映射成多种类型

  • Anonymous
  • Strongly Typed
  • Multi-Mapping
  • Multi-Result
  • Multi-Type
string sql = "SELECT * FROM Invoice;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var anonymousList = connection.Query(sql).ToList();
    var invoices = connection.Query<Invoice>(sql).ToList();
}

Utilities

  • Async
  • Buffered
  • Transaction
  • Stored Procedure
// Async
connection.QueryAsync<Invoice>(sql)

// Buffered
connection.Query<Invoice>(sql, buffered: false)

// Transaction
using (var transaction = connection.BeginTransaction())
{
    var affectedRows = connection.Execute(sql,
        new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
        commandType: CommandType.StoredProcedure,
        transaction: transaction);

    transaction.Commit();
}

// Stored Procedure
var affectedRows = connection.Execute(sql,
    new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
    commandType: CommandType.StoredProcedure);

执行非查询语句

 

描述

你可以从任意实现IDbConnection的类对象中调用Dapper的扩展方法“Execute”。它能够执行一条命令(Command)一次或者多次,并返回受影响的行数。这个方法通常用来执行:

  • Stored Procedure
  • INSERT statement
  • UPDATE statement
  • DELETE statement

参数

下面表格中显示了Execute方法的不同参数

 

名称 描述
sql

要执行的sql语句文本

param

command的参数

transaction

事务

commandTimeout

command超时时间

commandType

command类型

示例:执行存储过程

单次

执行存储过程一次

string sql = "EXEC Invoice_Insert";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
        new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"},
        commandType: CommandType.StoredProcedure);

    My.Result.Show(affectedRows);
}

多次

执行存储过程多次,数组中的每条数据都执行一次

string sql = "EXEC Invoice_Insert";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
        new[]
        {
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_1"},
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_2"}, new {Kind = InvoiceKind.StoreInvoice, Code = "Many_Insert_3"} }, commandType: CommandType.StoredProcedure ); My.Result.Show(affectedRows); }

示例:执行插入

单次

执行插入语句一次

 

string sql = "INSERT INTO Invoice (Code) Values (@Code);";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql, new {Kind = InvoiceKind.WebInvoice, Code = "Single_Insert_1"});

    My.Result.Show(affectedRows);
}

多次

执行多次,数组中的每条数据都执行一次

 

string sql = "INSERT INTO Invoice (Code) Values (@Code);";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
        new[]
        {
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_1"},
            new {Kind = InvoiceKind.WebInvoice, Code = "Many_Insert_2"}, new {Kind = InvoiceKind.StoreInvoice, Code = "Many_Insert_3"} } ); My.Result.Show(affectedRows); }

示例:执行Update

单次

执行Update语句一次

string sql = "UPDATE Invoice SET Code = @Code WHERE InvoiceID = @InvoiceID";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql, new {InvoiceID = 1, Code = "Single_Update_1"});

    My.Result.Show(affectedRows);
}

多次

执行多次,数组中的每条数据都执行一次

string sql = "UPDATE Invoice SET Code = @Code WHERE InvoiceID = @InvoiceID";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
        new[]
        {
            new {InvoiceID = 1, Code = "Many_Update_1"},
            new {InvoiceID = 2, Code = "Many_Update_2"}, new {InvoiceID = 3, Code = "Many_Update_3"} }); My.Result.Show(affectedRows); }

示例:执行Delete

单次

执行Delete语句一次

string sql = "DELETE FROM Invoice WHERE InvoiceID = @InvoiceID";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql, new {InvoiceID = 1});

    My.Result.Show(affectedRows);
}

多次

执行多次,数组中的每条数据都执行一次

string sql = "DELETE FROM Invoice WHERE InvoiceID = @InvoiceID";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var affectedRows = connection.Execute(sql,
        new[]
        {
            new {InvoiceID = 1},
            new {InvoiceID = 2}, new {InvoiceID = 3} }); }

 

 Dapper Query查询

介绍

查询方法(Query)是IDbConnection的扩展方法,它可以用来执行查询(select)并映射结果到C#实体(Model、Entity)类

查询结果可以映射成如下类型:

  • Anonymous 匿名类型
  • Strongly Typed 强类型
  • Multi-Mapping (One to One) 多映射 一对一
  • Multi-Mapping (One to Many) 多映射 一对多
  • Multi-Type 多类型

 

参数

下面表格中显示了Query方法的不同参数

 

名称 描述
sql

要执行的sql语句文本

param

command的参数

transaction

事务

buffered

True to buffer readeing the results of the query (default = true).

翻译不来。。。

commandTimeout

command超时时间

commandType

command类型

 

示例 - 匿名查询

Raw SQL query can be executed using Query method and map the result to a dynamic list.

直接执行SQL语句字符串,然后将结果映射成 dynamic类型的List中

string sql = "SELECT * FROM Invoice;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var invoices = connection.Query(sql).ToList();
    
    My.Result.Show(invoices);
}

 

 

示例 - 强类型查询(最常用)

直接执行SQL语句字符串,然后将结果映射成强类型类型的List中

string sql = "SELECT * FROM Invoice;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var invoices = connection.Query<Invoice>(sql).ToList();
    
    My.Result.Show(invoices);
}

示例 - 多映射查询 (One to One)

Raw SQL query can be executed using Query method and map the result to a strongly typed list with a one to one relation.(没太理解)

直接执行SQL语句字符串,然后将结果用一对一的关系映射成强类型类型的List中

string sql = "SELECT * FROM Invoice AS A INNER JOIN InvoiceDetail AS B ON A.InvoiceID = B.InvoiceID;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var invoices = connection.Query<Invoice, InvoiceDetail, Invoice>(
            sql,
            (invoice, invoiceDetail) =>
            {
                invoice.InvoiceDetail = invoiceDetail;
                return invoice; }, splitOn: "InvoiceID") .Distinct() .ToList(); My.Result.Show(invoices); }

示例 - 查询多映射 (One to Many)

Raw SQL query can be executed using Query method and map the result to a strongly typed list with a one to many relations.

直接执行SQL语句字符串,然后将结果用一对多的关系映射成强类型类型的List中

string sql = "SELECT * FROM Invoice AS A INNER JOIN InvoiceItem AS B ON A.InvoiceID = B.InvoiceID;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var invoiceDictionary = new Dictionary<int, Invoice>();

    var invoices = connection.Query<Invoice, InvoiceItem, Invoice>(
            sql,
            (invoice, invoiceItem) =>
            {
                Invoice invoiceEntry;
                
                if (!invoiceDictionary.TryGetValue(invoice.InvoiceID, out invoiceEntry)) { invoiceEntry = invoice; invoiceEntry.Items = new List<InvoiceItem>(); invoiceDictionary.Add(invoiceEntry.InvoiceID, invoiceEntry); } invoiceEntry.Items.Add(invoiceItem); return invoiceEntry; }, splitOn: "InvoiceID") .Distinct() .ToList(); My.Result.Show(invoices); }

示例 - Query Multi-Type

Raw SQL query can be executed using Query method and map the result to a list of different types.

string sql = "SELECT * FROM Invoice;";

using (var connection = My.ConnectionFactory())
{
    connection.Open();

    var invoices = new List<Invoice>();

    using (var reader = connection.ExecuteReader(sql))
    {
        var storeInvoiceParser = reader.GetRowParser<StoreInvoice>();
        var webInvoiceParser = reader.GetRowParser<WebInvoice>(); while (reader.Read()) { Invoice invoice; switch ((InvoiceKind) reader.GetInt32(reader.GetOrdinal("Kind"))) { case InvoiceKind.StoreInvoice: invoice = storeInvoiceParser(reader); break; case InvoiceKind.WebInvoice: invoice = webInvoiceParser(reader); break; default: throw new Exception(ExceptionMessage.GeneralException); } invoices.Add(invoice); } } My.Result.Show(invoices); }

 

参考文章:

dapper toturial  http://dapper-tutorial.net/dapper

http://dapper-tutorial.net/query

目录
相关文章
|
6月前
|
前端开发 API
bable 【实用教程】
bable 【实用教程】
45 1
|
8月前
|
存储 人工智能 搜索推荐
【LangChain系列】第六篇:内存管理简介及实践
【5月更文挑战第20天】【LangChain系列】第六篇:内存管理简介及实践
221 0
【LangChain系列】第六篇:内存管理简介及实践
|
8月前
|
人工智能 前端开发 机器人
【杂谈】扣子(Coze) 初体验
扣子(Coze)是什么 官方原文如下: 扣子(coze.cn)是一款用来开发新一代 AI Chat Bot 的应用编辑平台,无论你是否有编程基础,都可以通过这个平台来快速创建各种类型的 Chat Bot,并将其发布到各类社交平台和通讯软件上。 我们可以理解为一个聊天🤖️,可以在其他平台上发布。那就让我们快速开始吧
985 0
|
Web App开发 移动开发 JSON
谈一谈|谷歌插件入门
谈一谈|谷歌插件入门
322 0
|
设计模式 Java 测试技术
Workshop 深圳站|实战+源码架构剖析带你揭开Appium的神秘面纱
![](https://ceshiren.com/uploads/default/original/3X/f/3/f38d3f13105a1b79ada9bf315862ddfd0dbd87cf.jpeg) “工作坊(workshop)”一词 最早出现在教育与心理学的研究领域之中。它是引发人们思考、探讨、相互交流的一种方式,鼓励参与、创新、找出解决对策,Workshop是一种偏实战,注重实操性的
|
机器学习/深度学习 人工智能 自然语言处理
开源!《AI 算法工程师手册》中文教程正式发布!
开源!《AI 算法工程师手册》中文教程正式发布!
725 0
开源!《AI 算法工程师手册》中文教程正式发布!
|
SQL NoSQL Java
与图数据库、Gremlin语言的邂逅 -- 初体验
Gremlin语言是图数据库最主流的查询语言,是Apache TinkerPop框架下规范的图语言,相当于SQL之于关系型数据库。
与图数据库、Gremlin语言的邂逅 -- 初体验
|
机器学习/深度学习 人工智能 前端开发
|
SQL 安全 数据库
【快速入门ORM框架之Dapper】大牛勿进系列
原文:【快速入门ORM框架之Dapper】大牛勿进系列 前言:dapper是什么?Dapper是.NET下一个micro的ORM,它和Entity Framework或Nhibnate不同,属于轻量级的,并且是半自动的。
1552 0