Dapper入门教程(一)——Dapper介绍
Dapper是什么?
Dpper是一款.Net平台简单(Simple)的对象映射库,并且Dapper拥有着“微型ORM之王”的称号。就速度而言与手写ADO.NET SqlDateReader相同。ORM是Object Relational Mapper的缩写,代表着数据库与编程语言之间的映射。
Dapper的基本特性是通过扩展IDbConnection 接口,并为其提供查询数据库的方法。
Dapper是如何工作的?
将大象装冰箱总共分三步,Dapper也是如此。
- 创建IDBConnection对象(例如:SqlConnection)
- 编写用于CRUD的Sql语句
- 将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);
}
多次
执行存储过程多次,数组中的每条数据都执行一次
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
Dapper入门教程(一)——Dapper介绍的更多相关文章
- VB6 GDI+ 入门教程[1] GDI+介绍
http://vistaswx.com/blog/article/category/tutorial/page/2 VB6 GDI+ 入门教程[1] GDI+介绍 2009 年 6 月 18 日 17 ...
- RNN 入门教程 Part 3 – 介绍 BPTT 算法和梯度消失问题
转载 - Recurrent Neural Networks Tutorial, Part 3 – Backpropagation Through Time and Vanishing Gradien ...
- ASP.NET MVC4 新手入门教程之一 ---1.介绍ASP.NET MVC4
你会建造 您将实现一个简单的电影清单应用程序支持创建. 编辑. 搜索和清单数据库中的电影.下面是您将构建的应用程序的两个屏幕截图.它包括显示来自数据库的电影列表的网页: 应用程序还允许您添加. 编辑和 ...
- Dapper入门教程(二)——执行非查询语句
描述 你可以从任意实现IDbConnection的类对象中调用Dapper的扩展方法"Execute".它能够执行一条命令(Command)一次或者多次,并返回受影响的行数.这个方 ...
- Dapper入门教程(三)——Dapper Query查询
介绍 查询方法(Query)是IDbConnection的扩展方法,它可以用来执行查询(select)并映射结果到C#实体(Model.Entity)类 查询结果可以映射成如下类型: Anonymou ...
- JavaScript 入门教程一 开篇介绍
一.JavaScript 刚开始是为了解决一些由服务器端进行的验证而开发的前端语言.在宽带还不普及的90年代,当用户辛苦输入很多信息并提交给服务器后,等了漫长的时间,等到的不是提交成功的提示而是某些必 ...
- gitbook 入门教程之插件介绍
插件是 gitbook 的扩展功能,很多炫酷有用的功能都是通过插件完成的,其中插件有官方插件和第三方插件之分. 推荐官方插件市场 https://plugins.gitbook.com/ 寻找或下载相 ...
- Flutter开发移动端APP的入门教程及简单介绍
Dart&Flutter环境搭建 安装 dart SDK 如果只开发移动应用,那么您不需要Dart SDK; 只需安装Flutter. 这里就直接安装 Flutter (dart SDK已经集 ...
- 【electronjs入门教程 】electronjs 介绍
官网地址:https://electronjs.org/ 官网文档地址:https://electronjs.org/docs/ electronjs使用 JavaScript, HTML 和 CSS ...
随机推荐
- mybatis if test加筛选条件
最近在项目使用mybatis中碰到个问题 <if test="type=='y'"> and status = 0 </if> 当传入的type的值为y的时 ...
- 【分享】我们用了不到200行代码实现的文件日志系统,极佳的IO性能和高并发支持,附压力测试数据
很多项目都配置了日志记录的功能,但是,却只有很少的项目组会经常去看日志.原因就是日志文件生成规则设置不合理,将严重的错误日志跟普通的错误日志混在一起,分析起来很麻烦. 其实,我们想要的一个日志系统核心 ...
- JavaScript练习笔记整理·3 - 6.25
欢迎和大家一起来讨论~ 基础练习(1): 我的解答为: function array_diff(a, b) { if (b == "") return a; return ...
- 基于jQuery封装的分页组件
前言: 由于项目需要实现分页效果,上jQuery插件库找了下,但是木有找到自己想要的效果,于是自己封装了个分页组件. 思路: 主要是初始化时基于原型建立的分页模板然后绑定动态事件并实现刷新DOM的分页 ...
- JAVA基础——Arrays工具类十大常用方法
Arrays工具类十大常用方法 原文链接:http://blog.csdn.net/renfufei/article/details/16829457 0. 声明数组 String[] aArray ...
- Example005控制弹出窗口居中显示
<!-- 实例005控制弹出窗口居中显示 --> <head> <meta charset="UTF-8"> </head> < ...
- 如何使用LIBSVM,从安装到基本实例使用
1.在eclipse上安装libsvm 下载libsvm压缩包解压到本地目录,下载地址http://www.csie.ntu.edu.tw/~cjlin/libsvm/index.html 如图: 2 ...
- 前端如何将H5页面打包成本地app?
大家都知道H5页面怎么在手机浏览器里测试,但是如何能打包成APP测试呢?因为本人的手机是IOS系统,如果用Xcode打包需要开发证书,貌似99美元一年.意外发现一个叫Hbuild的软件,简单好用,下面 ...
- FAT文件系统学习和思考
FAT(File Allocation Table)文件系统 前两天面试,导师说我基础差,要赶紧补起来了.今天晚上看了FAT32文件系统,基本的信息都是百度百科中"FAT文件系统" ...
- 拥抱.NET Core系列:Logging (1)
在之前我们简单介绍了 .NET Core 中的 DI组件,没来及了解的童鞋可以翻翻我之前的文章. 接下来会对 .NET Core 中的 Logging 进行介绍. 本文中使用了"Micros ...