Dapper学习 - Dapper.Rainbow(一) - Create
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"}(我常用)形式的.