今天有人问我Update语句怎么搞,想了一下大致思路就是用特性去标识一下,主键,然后再去用反射的方式拼sql语句。
想着晚上再写,又想了想的确好久没写博客了,也好久没正儿八经写代码了,就顺手给写了下来。
一、主键特性
/// <summary> /// 主键特性(在实体类的上方加这个特性,指定该类的主键名称) /// </summary> [AttributeUsage(AttributeTargets.Class)] public class PrimaryKeyAttribute : Attribute { private PrimaryKeyAttribute() { } private string _name; /// <summary> /// 构造方法 /// </summary> /// <param name="name"></param> public PrimaryKeyAttribute(string name) { _name = name; } /// <summary> /// 主键名称 /// </summary> public string Name { get { return _name; } } }
把这个特性加到实体类的上方,并指定主键名称,就可以了,示例:
二、拼写SQL语句
public class SqlBuilderHelper { /// <summary> /// 获得主键名称 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> private static string GetPK<T>() where T : class { string pkName = string.Empty; Type objTye = typeof(T); PrimaryKeyAttribute pk; foreach (Attribute attr in objTye.GetCustomAttributes(true)) { pk = attr as PrimaryKeyAttribute; if (pk != null) return pk.Name; } return pkName; } /// <summary> /// sql修改语句 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <param name="tableName"></param> /// <returns></returns> public static string UpdateSql<T>(T entity, string tableName) where T : class { if (entity == null || string.IsNullOrEmpty(tableName)) { return string.Empty; } string pkName = GetPK<T>(); if (string.IsNullOrEmpty(pkName)) { return string.Empty; } string pkValue = string.Empty; StringBuilder sb = new StringBuilder(); sb.Append("update "); sb.Append(tableName); sb.Append(" set "); Type type = entity.GetType(); PropertyInfo[] props = type.GetProperties(); List<string> paraList = new List<string>(); foreach (var prop in props) { if (prop.Name == (string)pkName) { pkValue = (string)prop.GetValue(entity); } else { paraList.Add(GetUpdatePara(prop, entity)); } } if (paraList.Count == 0) { return string.Empty; } sb.Append(string.Join(",", paraList)); if (string.IsNullOrEmpty(pkValue)) { throw new Exception("主键不能为空"); } sb.Append(" where "); sb.Append(pkName); sb.Append(" = "); sb.AppendFormat("'{0}'", pkValue); return sb.ToString(); } /// <summary> /// 获得修改参数 /// </summary> /// <param name="property"></param> /// <returns></returns> private static string GetUpdatePara<T>(PropertyInfo property, T entity) { StringBuilder sb = new StringBuilder(); sb.AppendFormat(" {0}='{1}' ", property.Name, property.GetValue(entity)); return sb.ToString(); } }
用这个方法生成了一个语句,拿到库里面试了一下,完全ok。
大功告成。