Dapper
Dapper是一个轻量级ORM(Object Relationship Mapper)框架
Dapper和EF相比,EF开发效率快,省略了很多sql写法,但是运行效率慢,有时要考虑运行速度时就要用更快的ORM框架,其中有一个常用的就是Dapper
Dapper和EF一样支持多数据库
安装Dapper
install-package dapper
连接语句
使用dapper不需要考虑连接有没有打开,执行dapper是自行判断是否打开,如果没有打开自己会打开
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString)
数据库操作无非即使CURD操作,接下来介绍下基础的CURD操作,在那之前先创建一个Users表
Insert操作
1.单条insert操作
Users u = new Users() { UserName="XXX",Email="XXXXXXXX@qq.com",Address="XXXXXXX"};
con.Execute("insert into Users values(@UserName,@Email,@Address)", new { @name=u.UserName,u.Email,u.Address});//单条插入
如果Users类中属性和数据库的列相对应,可以简写为
Users u = new Users() { UserName="XXX",Email="XXXXXXXXXX@qq.com",Address="XXXXXXXXXXX"}; con.Execute("insert into Users values(@UserName,@Email,@Address)", u);//单条插入
2.批量insert操作
其实批量插入就是把对象改成集合
List<Users> userlist = new List<Users>() { new Users(){UserName="XXX",Email="XXXXXXX@qq.com",Address="XXXXXXXX"}, new Users(){UserName="XXXXX",Email="XXXXXXXXXX@qq.com",Address="XXXXXXXXXX"} }; con.Execute("insert into Users values(@UserName,@Email,@Address)",userlist); //批量插入
Update操作
修改其实就是改一下sql语句
Users u = new Users() {UserID=1,UserName="XXXXX"}; con.Execute("update Users set UserName=@UserName where UserID=@UserID",new { u.UserName,u.UserID});//修改
Delete操作
依然还是修改一下sql语句
con.Execute("delete from Users where UserID=@UserID",new { @UserID=1}); //删除
Select操作
1.无参数查询
var list = con.Query<Users>("select * from Users").ToList();//无参数查询
2.单条信息查询
var user = con.Query<Users>("select * from Users where UserID = @UserID",new { @UserID=1}).SingleOrDefault(); //单条查询
3.多条信息查询
var Userlist = con.Query<Users>("select * from Users where UserName=@UserName",new { @UserName="XXXXXXX"}).ToList(); //多条查询
4.SQL in(1,2,3) 多参数查询
var lists = con.Query<Users>("select * from Users where UserID in @IdArr",new { @IdArr=new int[] { 1,2,3} }); //多参数查询