/// <summary> /// 从本地变量缓存读取实体的SqlFieldMapping /// </summary> /// <param name="cacheKey"></param> /// <param name="acquire"></param> /// <returns></returns> public static SqlFieldMapping GetEntityMapping(string cacheKey, Func <SqlFieldMapping> acquire) { SqlFieldMapping cacheValue = null; if (Mappings.ContainsKey(cacheKey)) { cacheValue = Mappings[cacheKey]; return(cacheValue); } //不存在的话 ,那么执行委托并插入 cacheValue = acquire(); if (null != cacheValue) { Mappings.TryAdd(cacheKey, cacheValue); } return(cacheValue); }
/// <summary> /// 解析实体 解析其中的关联的表+字段+字段参数 /// </summary> /// <param name="isWriteCmd">是否是写入命令生成sql参数</param> internal SqlFieldMapping ResolveEntity(bool isWriteCmd) { var entity = this; string tableName = this.ResolveTableName(this); //----------尝试从静态字典中获取结构----------- string cacheKey = string.Concat(tableName, ":", Convert.ToInt32(isWriteCmd)); return(SqlFieldMappingManager.GetEntityMapping(cacheKey, () => { SqlFieldMapping mapping = new SqlFieldMapping(); mapping.TableName = tableName; #region 解析实体 //解析主键 var targetPrimaryKeyAttribute = this.GetType().GetCustomAttribute <PrimaryKeyAttribute>();// this.GetType().GetCustomAttributes(typeof(PrimaryKeyAttribute), false); if (targetPrimaryKeyAttribute != null) { var identityKeyModel = new EntityIdentity(); string name = targetPrimaryKeyAttribute.Name; identityKeyModel.IdentityKeyName = name; mapping.IdentityKey = identityKeyModel; } //获取所有字段 var fullPropertys = this.GetType().GetProperties(); //有效的db属性 var lstDbUsedPropertys = new List <PropertyInfo>(); var lstFilelds = new List <DbField>();//[propertys.Length]; for (int i = 0; i < fullPropertys.Length; i++) { var item = fullPropertys[i]; //将有忽略db的字段 排除 if (item.GetCustomAttribute <IgnoreDbFieldAttribute>() != null) { continue; //忽略属性 } if (isWriteCmd == true) { var writeAttr = item.GetCustomAttribute <WriteAttribute>(); if (null != writeAttr && writeAttr.Write == false) { continue; //如果是非写入参数,那么忽略此属性作为sql 参数 } } lstDbUsedPropertys.Add(item); //解析属性上的标注 CloumnAttribute string fieldName = item.Name; var colAttr = item.GetCustomAttribute <ColumnAttribute>(); if (null != colAttr && !colAttr.Name.IsNullOrEmpty()) { fieldName = colAttr.Name; //如果有自定义的ColumnAttribute } lstFilelds.Add(new DbField { PropertyName = item.Name, FieldColumnName = fieldName }); } //db 字段CLR 属性 mapping.Propertys = lstDbUsedPropertys.ToArray(); //字段 mapping.Filelds = lstFilelds; //参数字段 mapping.SqlParas = mapping.Filelds.Select(x => x.PropertyName).ToArray(); for (int i = 0; i < mapping.SqlParas.Length; i++) { mapping.SqlParas[i] = string.Concat("@", mapping.SqlParas[i]); } #endregion //保存到Mapping缓存 if (!SqlFieldMappingManager.Mappings.ContainsKey(cacheKey)) { SqlFieldMappingManager.Mappings.TryAdd(cacheKey, mapping); } return mapping; })); }