Dapper這個ORM有許多擴展, 我自己用過兩種, 也算是比較主流的兩種, Rainbow和Extension, 這裡就先介紹下Rainbow吧, 畢竟這個先用, 當然, 由於我使用的是mysql數據庫(項目中, java和.net結合的, 所以mssql用不了, 就用了mysql), 所以在使用Rainbow插件的時候, 需要修改一下, 這個不是針對mysql的.
由於時間關系, 先來介紹一下Create吧, 萬丈高樓Create起.
項目中下載Dapper.Rainbow的方法: PM>install-package dapper.rainbow
一、Create
在引用了下載後的程序集, 就可以開始編碼了
public class Rainbow : Database<Rainbow> { public Table<Tch_Teacher> Teacher { get; set; } public Table<Tch_Contact> Contact { get; set; } }
還是之前的那幾個類, 結構和名稱都沒有變.
測試代碼:
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.Insert(new Tch_Teacher() { BId = Guid.NewGuid().ToString(), CreateDate = DateTime.Now, IsDoublePosition = false, Name = "Haha" + i, No = i.ToString("000"), Sex = i % 2 }); } db.CommitTransaction(); } catch { db.RollbackTransaction(); Console.WriteLine("Error happened"); } } Console.ReadKey();
結果:
二、源碼解析
/// <summary> /// Insert a row into the db /// </summary> /// <param name="data">Either DynamicParameters or an anonymous type or concrete type</param> /// <returns></returns> public virtual int Insert(dynamic data) { var o = (object)data; //獲取字段/屬性 名稱 List<string> paramNames = GetParamNames(o); //去除Id, Rainbow默認每個表都有自增主鍵Id paramNames.Remove("Id"); string cols = string.Join(",", paramNames); //BId,CreateDate,IsDoublePosition,Name,No,Sex string cols_params = string.Join(",", paramNames.Select(p => "@" + p));//@BId,@CreateDate,@IsDoublePosition,@Name,@No,@Sex //var sql = "set nocount on insert " + TableName + " (" + cols + ") values (" + cols_params + ") select cast(scope_identity() as int)"; 原Rainbow語句 //修改部分 var sql = "insert " + TableName + " (" + cols + ") values (" + cols_params + ");SELECT LAST_INSERT_ID() AS LastInsertedId"; return database.Query<int>(sql, o).Single(); }
當LastInsertedId為null的時候, 會返回0, 並不影響結果
internal static List<string> GetParamNames(object o) { if (o is DynamicParameters) { return (o as DynamicParameters).ParameterNames.ToList(); } List<string> paramNames; if (!paramNameCache.TryGetValue(o.GetType(), out paramNames)) { paramNames = new List<string>(); foreach (var prop in o.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)) { var attribs = prop.GetCustomAttributes(typeof(IgnorePropertyAttribute), true); var attr = attribs.FirstOrDefault() as IgnorePropertyAttribute; if (attr == null || (attr != null && !attr.Value)) { paramNames.Add(prop.Name); } } paramNameCache[o.GetType()] = paramNames; } return paramNames; }
從上面的代碼可以看到, 如果不想更新某些字段, 可以在字段上面加上特性[IgnoreProperty], 還可以看到Insert的參數, 是一個動態對象, 不一定非得是Tch_Teacher, 也可以是別的類型, 例如 new {BId="111"}(我常用)形式的.