Dapper是.NET下一个micro的ORM,它和Entity Framework或Nhibnate不同,属于轻量级的,并且是半自动的,也就是说实体类都要自己写。可以实现数据到对象的ORM操作,体积小速度快(性能不错),使用ORM的好处是对数据的增、删、改查的速度很快,还有就是程序中大量的从数据库中读数据然后创建model,并为model字段赋值,Dapper都可以轻松完成。它没有复杂的配置文件,一个单文件就可以了。
优点
1. 使用Dapper可以自动进行对象映射。
2. 轻量级,单文件。
3. 支持多数据库。
4. Dapper原理通过Emit反射IDataReader的序列队列,来快速的得到和产生对象。
5. 可以映射一对一,一对多,多对多等多种关系。
dapper安装
在NuGet中搜索Dapper安装即可
dapper的使用
1. 连接语句
var _connectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString; IDbConnection conn = new SqlConnection(_connectionString);
使用dapper不需要考虑conn是否连接,在执行dapper时自行判断 open状态,如果没有打开它会自己打开。一条查询的时候不用管,多个查询在一起的时候,建议自己打开,写事务的时候还是需要自己打开的哦。
2. insert 插入数据
string query = "INSERT INTO Dogs(Id,Name,Age,Weight) VALUES(@Id,@Name,@Age,@Weight)"; conn.Execute(query,dog);
3. update 更新数据
query = "UPDATE Dogs SET Name=@name WHERE id =@id"; conn.Execute(query, dog);
4. delete 删除数据
query = "DELETE FROM Dogs WHERE id = @id"; conn.Execute(query, new { id = dog.Id });
5. query 查询操作
query = "SELECT * FROM Dogs"; var list = conn.Query<Dog>(query).ToList();
6. execute 执行增删改操作
上面的1,2,3操作
7. 批量插入
query = "INSERT INTO Dogs(Id,Name,Age,Weight) VALUES(@Id,@Name,@Age,@Weight)"; conn.Execute(query, new List<Dog>(){ new Dog{ Id = DateTime.Now.Ticks+1, Name = "小红1", Age = 2, Weight = 10 }, new Dog { Id = DateTime.Now.Ticks+2, Name = "小红2", Age = 2, Weight = 10 }, new Dog { Id = DateTime.Now.Ticks+3, Name = "小红3", Age = 2, Weight = 10 }, new Dog { Id = DateTime.Now.Ticks+4, Name = "小红3", Age = 2, Weight = 10 }, });
8. 多表查询
var sql = @"select * from #Posts p left join #Users u on u.Id = p.OwnerId Order by p.Id"; var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;}); var post = data.First();
9. 多结果查询
var sql = @" select * from Customers where CustomerId = @id select * from Orders where CustomerId = @id select * from Returns where CustomerId = @id"; using (var multi = connection.QueryMultiple(sql, new {id=selectedId})) { var customer = multi.Read<Customer>().Single(); var orders = multi.Read<Order>().ToList(); var returns = multi.Read<Return>().ToList(); ... }
10. 存储过程
var user = cnn.Query<User>("spGetUser", new {Id = 1},ommandType: CommandType.StoredProcedure).SingleOrDefault();
11. 特殊sql的处理,Dapper中in,like的使用
list = conn.Query<Dog>("SELECT * FROM Dogs WHERE id IN @ids ", new { ids = new long[] { list[0].Id, list[1].Id, list[2].Id } }).ToList(); list = conn.Query<Dog>("SELECT * FROM Dogs WHERE name LIKE @name ", new { name = $"%{name}%" }).ToList();
Gitub上源码地址
https://github.com/jasonhua95/Dapper.Extension.git