轻量级ORM框架Dapper(3)之数据的更新操作

数据的更新操作包括:Insert、Delete、Update
在Dapper中,我们使用提供的重载的扩展方法:

		 //
        // 摘要:
        //     Execute parameterized SQL.
        //
        // 参数:
        //    cnn:
        //     The connection to query on.
        //
        //   sql:
        //     The SQL to execute for this query.
        //
        //   param:
        //     The parameters to use for this query.
        //
        //   transaction:
        //     The transaction to use for this query.
        //
        //   commandTimeout:
        //     Number of seconds before command execution timeout.
        //
        //   commandType:
        //     Is it a stored proc or a batch?
        //
        // 返回结果:
        //     The number of rows affected.
        public static int Execute(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null);

其方法返回值:受影响行数

 		/// <summary>
        /// 批量处理
        /// 执行更新操作(增、删、改),不带事务处理
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="sql">SQL语句</param>
        /// <param name="t">泛型对象</param>
        public static void TestDapperUpdate<T>(string sql,List<T> t) {
            using (SqlConnection connect = new SqlConnection(ConnectStr)) { 
               int line=connect.Execute(sql,t);//调用Dapper的扩展方法Execute()执行更新操作,提交到数据库
                if (line>0) {
                    Console.WriteLine("数据成功更新!");
                }
            }
        }

我这里封装的是一个泛型方法:为了整个程序的扩展性,并且第二个参数为List

插入单条记录:

//插入单条记录
 string sql = @"INSERT INTO  ProductType(TypeName) VALUES(@TypeName)";
 List<ProductType> ptList = new List<ProductType>() {
     new ProductType(){TypeName="男装"}
 };
 TestDapperUpdate(sql,ptList);

Line Value:
在这里插入图片描述

批量插入数据:

 //批量插入多条数据
 string sql = @"INSERT INTO  ProductType(TypeName) VALUES(@TypeName)";
 List<ProductType> productTypeList = new List<ProductType>() {
      new ProductType(){ TypeName="家具"},
      new ProductType(){ TypeName="珠宝"},
      new ProductType(){ TypeName="特产"},
      new ProductType(){ TypeName="礼品鲜花"}
  };

  TestDapperUpdate(sql, productTypeList);

Result:
在这里插入图片描述
修改记录:
在这里插入图片描述
测试代码:

//修改单条记录
string sqlUpdated = @"UPDATE ProductType SET TypeName=@TypeName 
WHERE TypeId=@TypeId";
List<ProductType> productTypeUpdated = new List<ProductType>() {
 new ProductType(){ TypeId=4, TypeName="运动户外"}
 };

Result:
在这里插入图片描述
批量更新数据:
在这里插入图片描述

 //批量更新数据
string sqlUpdated = @"UPDATE ProductType SET TypeName=@TypeName 
WHERE TypeId=@TypeId";
List<ProductType> productTypeUpdatedList = new List<ProductType>() {
     new ProductType(){ TypeId=11, TypeName="个护清洁"},
     new ProductType(){ TypeId=12, TypeName="宠物"},
     new ProductType(){ TypeId=13, TypeName="汽车用品"},
     new ProductType(){ TypeId=14, TypeName="母婴"},
     new ProductType(){ TypeId=15, TypeName="玩具器乐"}
 };

 TestDapperUpdate(sqlUpdated, productTypeUpdatedList);

Result:
在这里插入图片描述
记录的删除:
删除单条记录:

string sqlDeleted = @"DELETE FROM ProductType WHERE TypeId=@TypeId";
//删除单条记录
  List<ProductType> productTypeDeleted = new List<ProductType>() {
      new ProductType(){ TypeId=5}
  };
  TestDapperUpdate(sqlDeleted, productTypeDeleted);

Result:记录已被删除
在这里插入图片描述
批量删除记录:

 //批量删除数据
string sqlDeleted = @"DELETE FROM ProductType WHERE TypeId=@TypeId";
List<ProductType> productTypeDeletedList = new List<ProductType>() {
     new ProductType(){ TypeId=11},
     new ProductType(){ TypeId=12},
     new ProductType(){ TypeId=13},
     new ProductType(){ TypeId=14}
 };
 TestDapperUpdate(sqlDeleted, productTypeDeletedList);

Result:记录都已被删除掉
在这里插入图片描述
至此,关于更新的操作大概在这里了,还有一些请看其他章节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Dapper .NET.NET 下一个简单的对象关系映射库 (ORM)。它支持SQLite, SQL CE, Firebird, Oracle, MySQL, PostgreSQL and SQL Server等数据库。   优点: 使用Dapper可以自动进行对象映射! 轻量级,单文件。 支持多数据库。 Dapper原理通过Emit反射IDataReader的序列队列,来快速的得到和产生对象。   Dapper.Net的示例代码: public class Dog {     public int? Age { get; set; }     public Guid Id { get; set; }     public string Name { get; set; }     public float? Weight { get; set; }     public int IgnoredProperty { get { return 1; } } }             var guid = Guid.NewGuid(); var dog = connection.Query("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid }); dog.Count()     .IsEqualTo(1); dog.First().Age     .IsNull(); dog.First().Id     .IsEqualTo(guid); 下面是Dapper .NET与其他几种数据访问组件的性能对比,从比较结果看Dapper .NET表现优异。 Performance of SELECT mapping over 500 iterations - POCO serialization Method Duration Remarks Hand coded (using a SqlDataReader) 47ms Can be faster Dapper ExecuteMapperQuery 49ms ServiceStack.OrmLite (QueryById) 50ms PetaPoco 52ms BLToolkit 80ms SubSonic CodingHorror 107ms NHibernate SQL 104ms Linq 2 SQL ExecuteQuery 181ms Entity framework ExecuteStoreQuery 631ms Performance of SELECT mapping over 500 iterations - dynamic serialization Method Duration Remarks Dapper ExecuteMapperQuery (dynamic) 48ms   Massive 52ms Simple.Data 95ms Performance of SELECT mapping over 500 iterations - typical usage Method Duration Remarks Linq 2 SQL CompiledQuery 81ms Not super typical involves complex code NHibernate HQL 118ms   Linq 2 SQL 559ms   Entity framework 859ms   SubSonic ActiveRecord.SingleOrDefault         github地址:https://github.com/StackExchange/dapper-dot-net 入门教程:http://www.cnblogs.com/Sinte-Beuve/p/4231053.html   Dapper已经有很多成熟的扩展项目了,Dapper.Rainbow、Dapper.Contrib,DapperExtensions   其中Dapper-Extensions非常不错,github地址:https://github.com/tmsmith/Dapper-Extensions Dapper-Extensions的优点: 1、开源 2、针对Dapper封装了常用的CRUD方法,有独立的查询语法。 3、需要映射的实体类本身0配置,无需加特性什么的。是通过独立的映射类来处理,可以设置类映射到DB的别名,字段的别名等等。 Dapper-Extensions的缺点: 1、好几年没更新了 2、不支持oracle(木有oracle的方言,已经搞定)  3、不能同时支持多种数据库(已经搞定) 4、部分代码有些bug(发现的都搞定了)   Dapper-Extensions入门教程可参考: http://www.cnblogs.com/hy59005271/p/4759623.html       标签:orm

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值