一、dapper是什么
dapper是一款轻量级的ORM(Object Relationship Mapper),它负责数据库和编程语言之间的映射。SqlConnection,MysqlConnection,OracleConnection都是继承于DBConnection,而DBConnection又是实现了IDBConnection的接口。因为Dapper是对IDBConnection接口进行了方法扩展,比如你看到的SqlMapper.cs,所以dapper支持多数据库。
二、dapper的简单使用
0、准备的测试类
1 //用户类 2 public class UserInfo 3 { 4 public int UId { get; set; }//用户Id 5 public string UserName { get; set; }//用户名 6 public int Age { get; set; }//年龄 7 public int RoleId { get; set; }//角色Id 8 9 } 10 //角色类 11 public class RoleInfo 12 { 13 public int RId { get; set; }//角色Id 14 public string RoleName { get; set; }//角色名 15 }
1、execute方法,返回值为int类型,表示受影响行数
1 //插入数据 2 //单条数据插入 3 int result = conn.Execute("insert into userinfo values(@username,@age,@roleid)", new 4 { 5 UserName = "user1", 6 Age = 20, 7 RoleId = 1 8 }); // result=1 9 10 //多条数据插入 11 Listusers=new List (){ 12 new UserInfo(){UserName="user2",Age=22,RoleId=1}, 13 new UserInfo(){UserName="user3",Age=23,RoleId=1}, 14 new UserInfo(){UserName="user4",Age=24,RoleId=2}, 15 }; 16 17 int result2 = conn.Execute("insert into userinfo values(@username,@age,@roleid)", users); // result2=3 18 19 //修改 20 int rusultEdit = conn.Execute("update userinfo set age=25 where username=@username", new { UserName = "user0" }); 21 22 //删除 23 int resultDel = conn.Execute("delete from userinfo where uid=@uid", new { UId = 6 });
2、Query方法,返回值为IEnumerable类型
1 //带参数查询 例子:查询用户名为user1,年龄为20的用户 2 IEnumerablequery1 = conn.Query ("select * from userinfo where age=@Age and username=@username", new{Age=20,UserName="user1"})
3 4 //in查询 例子:查询年龄是20,21,或22的用户 5 IEnumerablequery2=conn.Query ("select * from userinfo where age in @ages",new {ages=new int [3]{20,21,22}}); 6 7 //返回多个结果集 例子:查询用户列表和角色列表 8 var sql = "select * from userinfo; select * from roleinfo"; 9 var query3 = conn.QueryMultiple(sql);//GridReader类型 10 var usesList = query3.Read ();//IEnumberable类型 11 var roleList = query3.Read (); 12 13 //表连接查询 例子:查询用户信息和其对应的角色名 14 //1、返回强类型结果 15 var sql2 = @"select u.username,u.age,u.uid ,r.rolename from userinfo as u join roleinfo as r on u.roleid=r.rid"; 16 var result2 = conn.Query (sql2, (user, role) => 17 { 18 user.Role = role; 19 return user; 20 }, splitOn: "RoleName");//splitOn参数表示分割,前边的是第一个对象的属性,后边的是第二个对象的属性 21 22 //2、返回动态类型结果 23 var result3 = conn.Query(sql2); 24 foreach (var item in result3) 25 { 26 Console.WriteLine("username:{0},rolename:{1}", item.username, item.rolename); 27 }