public bool Exists <T>(int entityId, string primaryKey = "") { var ps = typeof(T).GetProperties(); if (string.IsNullOrEmpty(primaryKey)) { foreach (var propertyInfo in ps) { IdentityAttribute identity = IdentityAttribute.GetAttribute(propertyInfo); GuidIdentityAttribute guidIdentity = GuidIdentityAttribute.GetAttribute(propertyInfo); if (identity != null) { primaryKey = propertyInfo.Name; break; } else if (guidIdentity != null) { primaryKey = propertyInfo.Name; break; } } } if (string.IsNullOrEmpty(primaryKey)) { throw new Exception("没有指定主键"); } var sqlwhere = primaryKey + "=" + entityId; int count = GetCount <T>(sqlwhere); return(count > 0); }
private string GenerateUpdateSql(Type type, BaseEntity entity) { PropertyInfo[] propertyInfos = type.GetProperties(); TableInfoAttribute tableInfo = TableInfoAttribute.GetAttribute(type); string tableName = tableInfo == null ? type.Name : tableInfo.TableName; var updateString = new StringBuilder(); updateString.AppendFormat("UPDATE {0} SET ", tableName); int columnCount = 0; foreach (PropertyInfo info in propertyInfos) { ExtendedAttribute extended = ExtendedAttribute.GetAttribute(info); if (extended != null) { continue; } ExcludeFieldAttribute exclude = ExcludeFieldAttribute.GetAttribute(info); if (exclude != null) { continue; } IdentityAttribute identity = IdentityAttribute.GetAttribute(info); if (identity != null) { continue; } RefFieldAttribute refField = RefFieldAttribute.GetAttribute(info); if (refField != null) { continue; } GuidIdentityAttribute guidIdentity = GuidIdentityAttribute.GetAttribute(info); if (guidIdentity != null) { continue; } //var dbv = entity.Dbvalue.FirstOrDefault(p => p.Key == info.Name); //var newvalue = info.GetValue(entity, null); //if (dbv.Value != null && newvalue != null) // if (dbv.ToString() == newvalue.ToString()) continue; if (columnCount != 0) { updateString.Append(","); } updateString.AppendFormat("{0}=@{0}", info.Name); columnCount++; } if (columnCount == 0) { return(""); } return(updateString.ToString()); }
private string GenerateUpdateSql(Type type) { //判断缓存中存在已经生成的Sql语句,则直接返回 if (_updateSqlCaches.ContainsKey(type)) { return(_updateSqlCaches[type]); } PropertyInfo[] propertyInfos = type.GetProperties(); TableInfoAttribute tableInfo = TableInfoAttribute.GetAttribute(type); string tableName = tableInfo == null ? type.Name : tableInfo.TableName; var updateSql = new StringBuilder(); updateSql.AppendFormat("UPDATE {0} SET ", tableName); int columnCount = 0; foreach (PropertyInfo info in propertyInfos) { ExtendedAttribute extended = ExtendedAttribute.GetAttribute(info); if (extended != null) { continue; } ExcludeFieldAttribute exclude = ExcludeFieldAttribute.GetAttribute(info); if (exclude != null) { continue; } IdentityAttribute identity = IdentityAttribute.GetAttribute(info); if (identity != null) { continue; } RefFieldAttribute refField = RefFieldAttribute.GetAttribute(info); if (refField != null) { continue; } GuidIdentityAttribute guidIdentity = GuidIdentityAttribute.GetAttribute(info); if (guidIdentity != null) { continue; } if (columnCount != 0) { updateSql.Append(","); } updateSql.AppendFormat("{0}=@{0}", info.Name); columnCount++; } string updateString = updateSql.ToString(); _updateSqlCaches[type] = updateString; return(updateString); }
private PropertyInfo GetPrimaryKey(Type type) { PropertyInfo[] ps = type.GetProperties(); PropertyInfo pk = ps.FirstOrDefault(p => IdentityAttribute.GetAttribute(p) != null); if (pk == null) { pk = ps.FirstOrDefault(p => GuidIdentityAttribute.GetAttribute(p) != null); } return(pk); }
/// <summary> /// 添加一个实体 /// </summary> /// <param name="entity"></param> /// <returns></returns> public string AddEntity(BaseEntity entity) { //判断是否启用了缓存 Type type = entity.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(); var ps = new DynamicParameters { }; PropertyInfo pk = null; foreach (PropertyInfo propertyInfo in propertyInfos) { if (IdentityAttribute.GetAttribute(propertyInfo) != null) { pk = propertyInfo; } if (GuidIdentityAttribute.GetAttribute(propertyInfo) != null) { pk = propertyInfo; } if (ExcludeFieldAttribute.GetAttribute(propertyInfo) != null) { continue; } ps.Add(propertyInfo.Name, propertyInfo.GetValue(entity, null)); } string insertSql = GenerateInsertSql(type); try { using (IDbConnection connection = OpenConnection()) { string id = connection.Query <string>(insertSql, ps).FirstOrDefault(); if (pk != null) { pk.SetValue(entity, id, null); } return(id); } } catch (Exception ex) { throw new Exception("发生错误,SQL语句为:" + insertSql + "\r\n实体为:" + entity, ex); } }
/// <summary> /// 更新一个实体 /// </summary> /// <param name="entity"></param> /// <param name="primaryKeyField"></param> /// <returns></returns> public int UpdateEntity(BaseEntity entity, string primaryKeyField = "") { Type t = entity.GetType(); PropertyInfo[] ps = t.GetProperties(); PropertyInfo pk; if (string.IsNullOrEmpty(primaryKeyField)) { pk = ps.FirstOrDefault(p => IdentityAttribute.GetAttribute(p) != null); if (pk == null) { pk = ps.FirstOrDefault(p => GuidIdentityAttribute.GetAttribute(p) != null); } } else { pk = ps.FirstOrDefault(p => p.Name == primaryKeyField); } if (pk == null) { throw new Exception(string.Format("实体{0}没有设置主键", t.FullName)); } string where = " WHERE " + pk.Name + "=@" + pk.Name; string updateSql = ""; //if (entity.Dbvalue.Count == 0) updateSql = GenerateUpdateSql(t); //else // updateSql = GenerateUpdateSql(t, entity); if (string.IsNullOrWhiteSpace(updateSql)) { return(0); } updateSql += where; try { using (IDbConnection connection = OpenConnection()) { int result = connection.Execute(ToSqlServer(updateSql), entity, null, 60); return(result); } } catch (Exception ex) { throw new Exception("发生错误,SQL语句为:" + updateSql, ex); } }
/// <summary> /// 根据主键Id获取实体集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entityIds"></param> /// <returns></returns> public List <T> GetListByEntityIds <T>(IEnumerable <string> entityIds) where T : BaseEntity { T[] tArray = new T[entityIds.Count()]; IDictionary <string, int> objs = new Dictionary <string, int>(); for (int i = 0; i < entityIds.Count(); i++) { tArray[i] = default(T); objs[entityIds.ElementAt(i)] = i; } if (objs.Any()) { var entityType = typeof(T); var tableInfoAttr = TableInfoAttribute.GetAttribute(entityType); var pk = entityType.GetProperties().FirstOrDefault(p => IdentityAttribute.GetAttribute(p) != null); var tableName = tableInfoAttr == null ? entityType.Name : tableInfoAttr.TableName; if (pk == null) { pk = entityType.GetProperties().FirstOrDefault(p => GuidIdentityAttribute.GetAttribute(p) != null); } if (pk != null) { var idsString = ""; for (int i = 0; i < objs.Keys.ToArray().Length; i++) { idsString = idsString + (i == 0 ? ("'" + objs.Keys.ToArray()[i] + "'") : (",'" + objs.Keys.ToArray()[i] + "'")); } var datalist = FetchEntities <T>(tableName + "." + pk.Name + " IN(" + idsString + ")"); foreach (var entity1 in datalist) { tArray[objs[entity1.EntityId]] = entity1; } } } List <T> tEntities = new List <T>(); T[] tArray1 = tArray; for (int i = 0; i < tArray1.Length; i++) { T entity2 = tArray1[i]; if (entity2 != null) { tEntities.Add(entity2); } } return(tEntities); }
/// <summary> /// 生成新增的Sql语句 /// </summary> /// <param name="type"></param> /// <returns></returns> internal string GenerateInsertSql(Type type) { //判断缓存中存在已经生成的Sql语句,则直接返回 if (_insertSqlCaches.ContainsKey(type)) { return(_insertSqlCaches[type]); } PropertyInfo[] propertyInfos = type.GetProperties(); var insertSql = new StringBuilder(); bool hasIdentityField = false; TableInfoAttribute tableInfo = TableInfoAttribute.GetAttribute(type); string tableName = tableInfo == null ? type.Name : tableInfo.TableName; insertSql.AppendFormat("INSERT INTO {0} (", tableName); var values = new StringBuilder(" VALUES ("); int columnCount = 0; foreach (PropertyInfo info in propertyInfos) { ExtendedAttribute extended = ExtendedAttribute.GetAttribute(info); if (extended != null) { continue; } ExcludeFieldAttribute exclude = ExcludeFieldAttribute.GetAttribute(info); if (exclude != null) { continue; } IdentityAttribute identity = IdentityAttribute.GetAttribute(info); if (identity != null) { hasIdentityField = true; continue; } GuidIdentityAttribute guidIdentity = GuidIdentityAttribute.GetAttribute(info); if (guidIdentity != null) { hasIdentityField = true; } RefFieldAttribute refField = RefFieldAttribute.GetAttribute(info); if (refField != null) { continue; } if (columnCount != 0) { insertSql.Append(","); values.Append(","); } insertSql.AppendFormat("{0}", info.Name); values.AppendLine("@" + info.Name); columnCount++; } insertSql.AppendFormat(") {0} ) ", values); if (hasIdentityField) { insertSql.AppendFormat(_identity); } string insertSqlstr = insertSql.ToString(); _insertSqlCaches.Add(type, insertSqlstr); //加入缓存 return(insertSqlstr); }