標籤:value direction first proc etl 程式包 table 最佳化 public
首先我想說明一下:相比最原始的ADO.NET,一般都認為封裝過一層的ORM效能上會有損耗,但其實在使用中你會發現,當你需要把資料庫物件轉化為實體模型時,很多所謂的DbHelper其實封裝的很低效,反而是成熟的orm架構效能非常高;
在操作之前先在nuget裡擷取dapper和mysql.data的程式包:
插入資料:
/// <summary> /// 增加一條資料 /// </summary> public bool Add(User model) { int cnt = 0; 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); } if (cnt > 0) { return true; } else { return false; } }
刪除資料
/// <summary> /// 根據ID刪除一條資料 /// </summary> public bool Delete(int id) { int cnt = 0; string sQuery = "Delete FROM user " + "WHERE [email protected]"; using (var connection = new MySqlConnection(connstr)) { cnt = connection.Execute(sQuery, new { Id = id }); } if (cnt > 0) { return true; } else { return false; } }
修改資料
/// <summary> /// 更新一條資料 /// </summary> public bool Update(User model) { string sQuery = "UPDATE user SET [email protected]_Name,[email protected]_Pwd,[email protected]_Name,[email protected]_Num,[email protected]_Portrait,[email protected],[email protected]_Time,[email protected]_Time" + " WHERE [email protected]"; int cnt = 0; using (var connection = new MySqlConnection(connstr)) { cnt = connection.Execute(sQuery, model); } if (cnt > 0) { 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("@p_out_rows", 0, 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效能是很不錯的。
使用Dapper操作Mysql資料庫