首先我想说明一下:相比最原始的ADO.NET,一般都认为封装过一层的ORM性能上会有损耗,但其实在使用中你会发现,当你需要把数据库对象转化为实体模型时,很多所谓的DbHelper其实封装的很低效,反而是成熟的orm框架性能非常高;
在操作之前先在nuget里获取dapper和mysql.data的程序包:
插入数据:
/// <summary> /// 增加一条数据 /// </summary> public bool Add(User model) { ; string sQuery = "INSERT INTO user (Id,Login_Name,User_Pwd,User_Name,Phone_Num,Head_Portrait,Enabled,Create_Time,Update_Time)" + " VALUES(@Id,@Login_Name,@User_Pwd,@User_Name,@Phone_Num,@Head_Portrait,@Enabled,@Create_Time,@Update_Time)"; using (var connection = new MySqlConnection(connstr)) { cnt = connection.Execute(sQuery, model); } ) { return true; } else { return false; } }
删除数据
/// <summary> /// 根据ID删除一条数据 /// </summary> public bool Delete(int id) { ; string sQuery = "Delete FROM user " + "WHERE Id=@Id"; using (var connection = new MySqlConnection(connstr)) { cnt = connection.Execute(sQuery, new { Id = id }); } ) { return true; } else { return false; } }
修改数据
/// <summary> /// 更新一条数据 /// </summary> public bool Update(User model) { string sQuery = "UPDATE user SET Login_Name=@Login_Name,User_Pwd=@User_Pwd,User_Name=@User_Name,Phone_Num=@Phone_Num,Head_Portrait=@Head_Portrait,Enabled=@Enabled,Create_Time=@Create_Time,Update_Time=@Update_Time" + " WHERE Id=@Id"; ; using (var connection = new MySqlConnection(connstr)) { cnt = connection.Execute(sQuery, model); } ) { return true; } else { return false; } }
查询数据
/// <summary> /// 根据ID获取实体对象 /// </summary> public User GetModel(int id) { string sQuery = "SELECT Id,Login_Name,User_Pwd,User_Name,Phone_Num,Head_Portrait,Enabled,Create_Time,Update_Time FROM user " + "WHERE Id = @Id"; using (var connection = new MySqlConnection(connstr)) { return connection.Query<User>(sQuery, new { Id = id }).FirstOrDefault(); } }
调用分页存储过程
/// <summary> /// 分页获取数据列表 /// </summary> public IEnumerable<User> GetListByPage(int PageSize, int PageIndex, string strWhere, string orderStr, ref int rowsnum) { using (var connection = new MySqlConnection(connstr)) { var param = new DynamicParameters(); param.Add("@p_table_name", "user"); param.Add("@p_fields", "Id,Login_Name,User_Pwd,User_Name,Phone_Num,Head_Portrait,Enabled,Create_Time,Update_Time"); param.Add("@p_page_size", PageSize); param.Add("@p_page_now", PageIndex); param.Add("@p_where_string", strWhere); param.Add("@p_order_string", orderStr); param.Add(, DbType.Int32, ParameterDirection.Output); IEnumerable<User> infoList = connection.Query<User>("pr_pager", param, null, true, null, CommandType.StoredProcedure); rowsnum = param.Get<int>("@p_out_rows"); return infoList; }
在不进行任何代码特殊优化的测试中,同过Emit反射IDataReader的序列队列,来快速的得到和产生对象的dapper性能是很不错的。