上一篇介紹了Rainbow的Create方法, 這裡就來介紹一下Update方法吧, 畢竟新增和修改是雙胞兄弟嘛.
一、Update
1. 測試代碼:
var conStr = ConfigurationManager.ConnectionStrings["Cons"].ToString(); using (var conn = new MySqlConnection(conStr)) { var db = Rainbow.Init(conn, 2000); try { db.BeginTransaction(); for (int i = 0; i < 10; i++) { var res = db.Teacher.Update(i + 1, new { //BId = Guid.NewGuid().ToString(), //CreateDate = DateTime.Now, // IsDoublePosition = Convert.ToBoolean(i % 2), Name = "Xixi" + i, No = (i * 100 + i).ToString("000"), //Sex = i % 2 }); } db.CommitTransaction(); } catch { db.RollbackTransaction(); Console.WriteLine("Error happened"); } }
使用方法和Insert方法類似, Update方法由兩個參數, 第一個參數是Id, 第二個參數是dynamic data, 如果你不想更新全部的列, 只需要新建一個實體, 裡面只包含你想更新的列就行了, 這樣做, 不會修改到別的列.
結果:
2. 源碼解析
/// <summary> /// Update a record in the DB /// </summary> /// <param name="id"></param> /// <param name="data"></param> /// <returns></returns> public int Update(TId id, dynamic data) { List<string> paramNames = GetParamNames((object)data); var builder = new StringBuilder(); builder.Append("update ").Append(TableName).Append(" set "); builder.AppendLine(string.Join(",", paramNames.Where(p => p != "Id").Select(p => p + "= @" + p))); builder.Append(" where " + "Id" + " = @Id"); DynamicParameters parameters = new DynamicParameters(data); parameters.Add("Id", id); return database.Execute(builder.ToString(), parameters); }
Dapper這裡是通過反射傳入參數data, 來提取其中的字段名稱, 生成一個List<string>集合, 然後根據這個集合去拼接sql語句.
如果你的框架中, 數據庫設計遵循的規則, 有CreateBy, CreateTime字段, 在我們獲取到實體時, 就是Tch_Teacher的格式, 但是我們又不想再寫一遍new{}, 或者dynamic obj = new ExpandoObject()的時候, 就可以從Update方法入手, 修改一下就可以省下許多事情.
builder.AppendLine(string.Join(",", paramNames.Where(p => p != "Id" && p != "CreateBy" && p != "CreateTime").Select(p => p + "= @" + p)));
二、Delete
1. 測試代碼
var conStr = ConfigurationManager.ConnectionStrings["Cons"].ToString(); using (var conn = new MySqlConnection(conStr)) { var db = Rainbow.Init(conn, 2000); try { db.BeginTransaction(); for (int i = 0; i < 10; i+=2) { var res = db.Teacher.Delete(i); } db.CommitTransaction(); } catch { db.RollbackTransaction(); Console.WriteLine("Error happened"); } }
刪除方法就很簡單了, Rainbow只提供了一個根據主鍵刪除的方法, 這裡可以擴展成Update的那種方式, 可以根據所傳入的字段來匹配刪除數據
2. 源碼解析
先看Rainbow的源碼, 這裡就沒有什麼好說明的了
/// <summary> /// Delete a record for the DB /// </summary> /// <param name="id"></param> /// <returns></returns> public bool Delete(TId id) { return database.Execute("delete from " + TableName + " where " + "Id" + " = @id", new { id }) > 0; }
下面來看一下, Delete的訂制擴展方法
/// <summary> /// 自定義刪除方法 /// 根據傳入字段來刪除數據 /// </summary> /// <param name="data"></param> /// <returns></returns> public bool Delete(dynamic data) { List<string> paramNames = GetParamNames((object)data); var builder = new StringBuilder(); builder.Append("delete from ").Append(TableName).Append(" where "); builder.Append(string.Join(" and ", paramNames.Select(n => n + "=@" + n))); return database.Execute(builder.ToString(), data) > 0; }
這裡的刪除, 都是 and 連接, 如果想要 or , instr()>0 方式的, 那就只有自己寫sql了, 這裡並不提供此類方法
/// <summary> /// Delete a record for the DB /// </summary> /// <param name="id"></param> /// <returns></returns> public bool DeleteWhere(string where, dynamic param = null) { string wherestr = ""; if (!string.IsNullOrEmpty(where)) wherestr = " where " + where; return database.Execute("delete from " + TableName + wherestr, param) > 0; }
可以自己寫一個, 只要給條件就行了, 不過這個方法是有蠻大風險的, 如果where為空, 會清空表