一、安装
在https://www.nuget.org中查找Dapper,显示如下:
我们在VS的程序包管理控制台输入安装命令Install-Package Dapper即可
二、简介
Dapper作为一款轻量级ORM工具,那什么是ORM呢?
ORM就是Object-Relational Mapping(对象-关系映射,简称ORM),对象和关系数据是业务实体的两种表现形式,ORM就相当于一个中间件,起到了对象和数据库数据之间的映射。
三、基本用法
我们建立了两张表UserInfo和UserAccount和对应的类UserInfo和Users,首先要做的就是连接数据库
const string _connectionString = "Data Source=.;Initial Catalog=RekTecTest;Integrated Security=True;MultipleActiveResultSets=True";
using (IDbConnection connection = new SqlConnection(_connectionString))
{
}
接着我们插入数据到新建的表中
//插入一条对象
var result = connection.Execute("Insert into UserAccount values (@UserName, @UserID, @PassWord,@CreateTime)",
new { UserName = "jack", UserID = "10081", PassWord = "123451", CreateTime = "2018-3-1 19:18:19" });
connection.Execute("Insert into UserInfo(Name,Address) values (@username,@Address)",
new { username = "张三", Address = "苏州" });
这里我们插入的是一个匿名对象,可以将数据库的参数省略不写。
当然也可以批量插入
connection.Execute("insert into UserInfo(Address,Name) values(@address,@name)",
new[] {
new { Address = "上海", Name = "李四" },
new { Address = "北京", Name = "王五" },
new { Address = "杭州", Name = "赵六" }
});
或者
var usersList = Enumerable.Range(0, 5).Select(i => new Users()
{
UserName = "jack" + i,
UserID = 10000 + i,
PassWord = "jack"+i,
CreateTime = "2018-3-1 19:25:06"
});
var result = connection.Execute("Insert into UserAccount values(@UserName, @UserID, @PassWord,@CreateTime)", usersList);
查询
//查询-参数化查询
var query = connection.Query("select * from UserAccount where UserName=@UserName and UserID=@UserID", new { UserName = "李四", UserID = 1002 });
Console.WriteLine(query.FirstOrDefault().UserName);
将查询结果映射到匿名类型
var result = connection.Query("select top 10 * from UserInfo");
var resultList = result.AsList();
foreach (var l in resultList)
Console.WriteLine(l.Name);
关联查询
var result = connection.Query("select u1.Name,u2.UserID from UserInfo u1,UserAccount u2 where u1.Name=u2.UserName",
(u1, u2) =>
{
return u1.Name + " " + u2.UserID;
},
splitOn: "UserID");
foreach (var r in result)
{
Console.WriteLine(r);
}
查询多个
string sql = "select * from UserInfo;select * from UserAccount";
using (varmultipleReader=connection.QueryMultiple(sql)
{
var userInfo=multipleReader.Read();
var users =multipleReader.Read();
}
更新
connection.Execute("update UserAccount set UserName=@UserName where UserID=@UserID", new{UserName="CurryZhang", UserID = 10081 });
删除
connection.Execute("delete from UserAccount where UserName like '%jack%'");
//删除-参数化
//connection.Execute("delete from UserAccount where UserName=@name",new { name="张飞"});
四.、ORM的优缺点
优点:
1)提高开发效率,降低开发成本
2)使开发更加对象化
3)可移植
4)可以很方便地引入数据缓存之类的附加功能
缺点:
1)自动化进行关系数据库的映射需要消耗系统性能。其实这里的性能消耗还好啦,一般来说都可以忽略之。
2)在处理多表联查、where条件复杂之类的查询时,ORM的语法会变得复杂。
五、Dapper优点
- Dapper是一个轻量级的ORM框架,它是通过扩展IDbConnection接口来实现一系列的功能的。相比EF、NHibernate,它的功能较为简单。
- Dapper在执行查询语句时会缓存SQL语句的相关信息,这样就保证了Dapper拥有较高的性能