Dapper入门教程(一)——Dapper介绍

时间:2022-06-08 13:11:42

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 = });
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 = , 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);
}

Dapper入门教程(一)——Dapper介绍

多次

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

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);
}

Dapper入门教程(一)——Dapper介绍

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

直接执行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);
}

Dapper入门教程(一)——Dapper介绍

示例 - 多映射查询 (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);
}

Dapper入门教程(一)——Dapper介绍

示例 - 查询多映射 (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);
}

Dapper入门教程(一)——Dapper介绍

示例 - 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入门教程(一)——Dapper介绍

参考文章:

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

http://dapper-tutorial.net/query

Dapper入门教程(一)——Dapper介绍的更多相关文章

  1. VB6 GDI&plus; 入门教程&lbrack;1&rsqb; GDI&plus;介绍

    http://vistaswx.com/blog/article/category/tutorial/page/2 VB6 GDI+ 入门教程[1] GDI+介绍 2009 年 6 月 18 日 17 ...

  2. RNN 入门教程 Part 3 – 介绍 BPTT 算法和梯度消失问题

    转载 - Recurrent Neural Networks Tutorial, Part 3 – Backpropagation Through Time and Vanishing Gradien ...

  3. ASP&period;NET MVC4 新手入门教程之一 ---1&period;介绍ASP&period;NET MVC4

    你会建造 您将实现一个简单的电影清单应用程序支持创建. 编辑. 搜索和清单数据库中的电影.下面是您将构建的应用程序的两个屏幕截图.它包括显示来自数据库的电影列表的网页: 应用程序还允许您添加. 编辑和 ...

  4. Dapper入门教程(二)——执行非查询语句

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

  5. Dapper入门教程(三)——Dapper Query查询

    介绍 查询方法(Query)是IDbConnection的扩展方法,它可以用来执行查询(select)并映射结果到C#实体(Model.Entity)类 查询结果可以映射成如下类型: Anonymou ...

  6. JavaScript 入门教程一 开篇介绍

    一.JavaScript 刚开始是为了解决一些由服务器端进行的验证而开发的前端语言.在宽带还不普及的90年代,当用户辛苦输入很多信息并提交给服务器后,等了漫长的时间,等到的不是提交成功的提示而是某些必 ...

  7. gitbook 入门教程之插件介绍

    插件是 gitbook 的扩展功能,很多炫酷有用的功能都是通过插件完成的,其中插件有官方插件和第三方插件之分. 推荐官方插件市场 https://plugins.gitbook.com/ 寻找或下载相 ...

  8. Flutter开发移动端APP的入门教程及简单介绍

    Dart&Flutter环境搭建 安装 dart SDK 如果只开发移动应用,那么您不需要Dart SDK; 只需安装Flutter. 这里就直接安装 Flutter (dart SDK已经集 ...

  9. 【electronjs入门教程 】electronjs 介绍

    官网地址:https://electronjs.org/ 官网文档地址:https://electronjs.org/docs/ electronjs使用 JavaScript, HTML 和 CSS ...

随机推荐

  1. 设置 phoneGap&sol;Cordova 3&period;4 应用程序启动动画闪屏 SplashScreen

    当Cordova 程序打包并安装到手机中后,我们会发现启动程序时,会有数秒的黑屏现象,常见的解决方法则是设置闪屏后面. 这里以 Android 程序为例,介绍Cordova设置启动画面的方法. 1. ...

  2. html&comma;CSS文字大小单位px、em、pt的关系换算

    html,CSS文字大小单位px.em.pt的关系换算 这里引用的是Jorux的“95%的中国网站需要重写CSS”的文章,题目有点吓人,但是确实是现在国内网页制作方面的一些缺陷.我一直也搞不清楚px与 ...

  3. 2014年度辛星html教程夏季版第五节

    如果读者是一位后台开发者,那么肯定会知道什么叫表单,这里我们就介绍一下前台如何使用表单,表单的使用也是我们编写网页的必须经历的一关,而且,表单也往往是我们网站的漏洞和弱点出现的地方. ******** ...

  4. 定时执行 Job - 每天5分钟玩转 Docker 容器技术(135)

    Linux 中有 cron 程序定时执行任务,Kubernetes 的 CronJob 提供了类似的功能,可以定时执行 Job.CronJob 配置文件示例如下: ① batch/v2alpha1 是 ...

  5. XML错误信息Referenced file contains errors &lpar;http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;beans&sol;spring-beans-4&period;0&period;xsd&rpar;&period; For more information&comma; right click on the message in the Problems View &period;&period;&period;

    错误信息:Referenced file contains errors (http://www.springframework.org/schema/beans/spring-beans-4.0.x ...

  6. CentOS下安装nvm

    1安装版本管理工具git yum install git 查看git版本 git --version 2 安装Node.js版本管理工具nvm curl -o- https://raw.githubu ...

  7. DataTable转实体类

    /// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...

  8. python代码块,小数据池,驻留机制深入剖析

    一,什么是代码块. 根据官网提示我们可以获知: 根据提示我们从官方文档找到了这样的说法: A Python program is constructed from code blocks. A blo ...

  9. Q in Q

    简介 Q in Q技术(也称Stacked VLAN 或Double VLAN).标准出自IEEE 802.1ad,将用户私网VLAN Tag封装在公网VLAN Tag中,使报文带着两层VLAN Ta ...

  10. linux查看某个目录下有哪些文件的命令

    分别是ll和ls命令 ll /usr/local/lib ls /usr/local/lib