.NET技术-2.0. 操作数据库-Dapper
项目参见:
1. 为什么选择Dapper
1) 性能优越:
其实在各大网站上,我们大概都会看到这样的一个对比效果图,在超过500次poco serialization的过程中所表现的性能,我们发现dapper是第二名,
当然第一名谁也无法超越,越底层的当然久越快,同时也就越麻烦。就好像谁能超过“01代码”呢???
2) 支持多数据库
支持多数据库的本质是因为Dapper是对IDBConnection接口进行了方法扩展,比如你看到的SqlMapper.cs,一旦你这样做了,我们也知道,
SqlConnection,MysqlConnection,OracleConnection都是继承于DBConnection,而DBConnection又是实现了IDBConnection的接口,对吧。。。
2. 安装 Dapper
Install-Package Dapper
3. 无事务的操作
IDbConnection connection = DB.Database.GetDbConnection(); //查询 var queryRes = connection.Query<TblOrder>("select * from tbl_order where amount=@amount", new { amount = "10" }).ToList(); //新增 List<Models.TblOrder> list = new List<TblOrder>() {new TblOrder() { Amount = 10, Uptime= DateTime.Now, Order_Code = "119", User_Id = 2 ,Text="aaaa"}, new TblOrder() { Amount = 10, Uptime= DateTime.Now, Order_Code = "118", User_Id = 2 ,Text="bbbbb"}, new TblOrder() { Amount = 10, Uptime= DateTime.Now, Order_Code = "117", User_Id = 2 ,Text="ccccc"}}; string str = "INSERT INTO tbl_order (order_code,user_id,amount,uptime,text) VALUES(@order_code,@user_id,@amount,@uptime,@text)"; connection.Execute(str, list); //修改 list = connection.Query<TblOrder>("select * from tbl_order where order_code=@order_code", new { order_code = "117" }).ToList(); str = "UPDATE tbl_order SET Text='abcabc' where order_code=@order_code"; connection.Execute(str, list); //删除 list = connection.Query<TblOrder>("select * from tbl_order order by id").ToList(); connection.Execute("delete from tbl_order where id =@id", list.Take(2).ToList());
4. 带事务的操作
using (IDbConnection connection = DB.Database.GetDbConnection()) { connection.Open(); IDbTransaction transaction = connection.BeginTransaction(); try { //修改 var list = connection.Query<TblOrder>("select * from tbl_order where order_code=@order_code", new { order_code = "119" }).ToList(); string str = "UPDATE tbl_order SET Text='开心开心' where order_code=@order_code"; connection.Execute(str, list,transaction); //删除 list = connection.Query<TblOrder>("select * from tbl_order order by id").ToList(); connection.Execute("delete from tbl_order where id =@id", list.Take(2).ToList(), transaction); transaction.Commit(); } catch (Exception exception) { transaction.Rollback(); } }
引用:https://www.cnblogs.com/huangxincheng/p/5828470.html