public static IEnumerable <T> LoadObjectList <T>(Dictionary <string, object> filter = null) where T : TObject { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DBTableAttribute)); TStorage tStorage = new TStorage { Fields = filter, Table = dbTableAttribute.Table }; TrackingServiceClient tsc = new TrackingServiceClient(); IEnumerable <TStorage> tStorageList = tsc.LoadList(tStorage); List <T> result = new List <T>(); foreach (TStorage s in tStorageList) { var ctor = typeof(T).GetConstructor(new Type[] { }); var item = ctor.Invoke(new object[] { }) as T; item.SetKeyValuePairs(s.Fields); item.SetKeyValue(s.Fields[item.GetKeyField()]); result.Add(item); } return(result); }
/// <summary> /// 获取扩展类的 /// </summary> /// <param name="table"></param> /// <param name="attrs"></param> /// <returns></returns> private static string DoPartialCode(DBTableAttribute table, List <System.Attribute> attrs, Type p) { string className = p.Name.StartsWith("m_") ? p.Name.Substring(2, p.Name.Length - 2) : p.Name;//设置类名 StringBuilder attrBuilder = new StringBuilder(); //todo 实现该类 attrBuilder.Append(" #region 外部可直接访问 注释:").Append(p.FullName).AppendLine(table.Description); attrBuilder.AppendLine(" /// <summary>"); attrBuilder.AppendLine(" /// 模板生成"); attrBuilder.Append(" /// CreateBy 童岭 ").AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); attrBuilder.Append(" /// ").AppendLine(table.Description); attrBuilder.Append(" /// ").Append(table.TableName).Append("表所属用户 ").AppendLine(table.BelongToDBUser); attrBuilder.AppendLine(" /// </summary>"); attrBuilder.Append(" public partial class dl_").AppendLine(className); attrBuilder.AppendLine(" {"); attrBuilder.Append(" private static readonly string _dbUser = "******"System.Configuration.ConfigurationSettings.AppSettings[\"app_user\"].ToString()"); } else { attrBuilder.Append("\"").Append(table.BelongToDBUser).Append("\""); } attrBuilder.Append(";//定义该表数据库访问用户"); foreach (var attr in attrs) //遍历每一个特性 { if (attr is Attribute.IReleaseMaker) //如果其实现了ICodeBuildMaker 接口 { attrBuilder.AppendLine((attr as Attribute.IReleaseMaker).CreateCode(table, p)); //添加方法 } } return(attrBuilder.AppendLine(" }").AppendLine(" #endregion").ToString()); }
/// <summary> /// 逻辑删除 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="info">实体</param> /// <returns>删除行数</returns> public int LogicDelete <T>(T info) where T : new() { int count = 0; string tableName = ""; string sql = ""; string where = ""; string UPDATEUSR = ""; T oldInfo = default(T); DataChangeManageDAL markManager = new DataChangeManageDAL(); List <DataParameter> parameters = new List <DataParameter>(); try { //获取表名 Type type = typeof(T); object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = tableAtt.TableName; //获取主键信息 Dictionary <string, object> pkColumns = new DataQueryHelper().GetPkColumns <T>(info); UPDATEUSR = BindHelper.GetPropertyValue(info, "UPDATEUSER") == null ? "" : BindHelper.GetPropertyValue(info, "UPDATEUSER").ToString(); //获取原实体 oldInfo = (T)(info as BaseEntity).Clone(); oldInfo = this.BaseSession.Get <T>(info); //获取数据主键 string dataID = this.GetEntityDataID <T>(info); //逻辑删除 sql = string.Format("UPDATE {0} SET FLGDEL='1',UPDATEDATE=GETDATE(),UPDATEUSER=@UPDATEUSER WHERE ", tableName, UPDATEUSR); parameters.Add(new DataParameter("UPDATEUSER", UPDATEUSR)); foreach (string key in pkColumns.Keys) { where += " AND " + key + " = @" + key; parameters.Add(new DataParameter(key, pkColumns[key])); } sql += where.Substring(4); sql = this.ChangeSqlByDB(sql, this.BaseSession); count = this.BaseSession.ExecuteSql(sql, parameters.ToArray()); //记录痕迹 markManager.Session = this.BaseSession; //markManager.RecordDataChangeMarkDetail<T>(DataOprType.Delete, UPDATEUSR, dataID, oldInfo, info); return(count); } catch (Exception ex) { throw ex; } }
public string getQueryList(Type source, DBFieldMetadata[] criteria) { if (!isAnalyzed(source)) { analyze(source); } DBTableAttribute classTable = getClassTable(source); DBFieldMetadata[] dbFields = getAllFields(source); StringBuilder sb = new StringBuilder(); sb.Append("SELECT "); for (int i = 0; i < dbFields.Length - 1; i++) { sb.Append(dbFields[i].ColumnName).Append(", "); } sb.Append(dbFields[dbFields.Length - 1].ColumnName); sb.Append(" FROM ").Append(dbFields[0].TableName); sb.Append(" WHERE 1=1"); if (criteria != null) { for (int i = 0; i < criteria.Length; i++) { sb.Append(" AND ").Append(criteria[i].ColumnName).Append(" = ?"); } } return(sb.ToString()); }
public IEnumerable <TMeasurement> GetAll() { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(BMeasurement), typeof(DBTableAttribute)); TStorage q = new TStorage { Table = dbTableAttribute.Table }; var storageItems = LoadList(q); List <TMeasurement> measurements = new List <TMeasurement>(); foreach (var si in storageItems) { TMeasurement m = new TMeasurement { TMeasurementId = (int)(si.Fields[BMeasurement.KeyParm.Key]), Text = (string)(si.Fields[BMeasurement.TextParm.Key]), Description = (string)(si.Fields[BMeasurement.DescriptionParm.Key]), PhotoClientPath = (string)(si.Fields[BMeasurement.PhotoClientPathParm.Key]), PhotoServerPath = (string)(si.Fields[BMeasurement.PhotoServerPathParm.Key]) }; measurements.Add(m); } return(measurements); }
/// <summary> /// 构造函数 /// </summary> /// <param name="type">映射类型</param> /// <param name="tbName">表名</param> /// <param name="cacheType">表数据缓存方式</param> /// <param name="separateType">数据库表拆分方式</param> /// <param name="createSql">创建表的sql语句</param> /// <param name="separateFieldName">数据表拆分字段</param> /// <param name="separateIDHashNum"></param> /// <param name="cacheSeconds">是否缓存</param> public DBTable(Type type, string tbName, DBTableAttribute attr) { this.MapType = type; this.AliasName = type.Name; this.Name = tbName; this.CacheType = attr.CacheType; this.SeparateType = attr.SeparateType; this.CreateSql = attr.CreateSql; if (this.SeparateType != SeparateType.None && string.IsNullOrWhiteSpace(this.CreateSql)) { throw new MyDBException(string.Format("表{0}没有配置创建SQL语句", tbName)); } this.CacheSeconds = attr.CacheSeconds; PrimaryKey = new List <DBPrimaryKey>(); ColumnList = new List <DBColumn>(); //初始化字段列表 GetFieldList(type); if (PrimaryKey.Count == 0) { throw new Exception(string.Format("表{0}未映射主键", this.Name)); } if (PrimaryKey.Count > 1 && PrimaryKey[0].DBPrimaryType == DBPrimaryType.Identity) { throw new Exception(string.Format("表{0}联合主键不支持自增长", this.Name)); } if (PrimaryKey.Count > 1 && this.SeparateType != DBFrame.SeparateType.None) { throw new Exception(string.Format("表{0}联合主键不支持表拆分", this.Name)); } }
private void cache(string key, DBFieldMetadata[] allFields, DBFieldMetadata[] identityFields, DBFieldMetadata[] appValuedFields, DBFieldMetadata autoIdentityField, DBTableAttribute classAttribute) { _cacheAllFields.put(key, allFields); _cacheAppValuedFields.put(key, appValuedFields); _cacheClassTables.put(key, classAttribute); _cacheIdentities.put(key, identityFields); _cacheAutoIdentityField.put(key, autoIdentityField); }
/// <summary> /// 删除实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <returns>删除行数</returns> public virtual int Delete <T>(T model) where T : new() { int count = 0; Type type = null; string sql = ""; string tableName = ""; string whereSql = ""; List <DataParameter> parameters = null; try { type = typeof(T); //获取表信息 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = this.DbHelper.GetDbObjectName(tableAtt.TableName); //获取删除条件 this.GetSingleWhere <T>(model, out whereSql, out parameters); if (string.IsNullOrEmpty(whereSql) == true) { throw new Exception("删除条件提取失败,不能执行删除操作!"); } //构成删除语句 sql = string.Format("delete from {0} where {1}", tableName, whereSql); this.OpenCon(); //执行语句 count = this.DbHelper.ExecuteSql(sql, parameters, this.Connection, this.Transaction); return(count); } catch (Exception ex) { this.RollbackTs(); throw ex; } finally { this.CloseCon(); //记录日志 this.RecordLog(sql, parameters); } }
/// <summary> /// 初始化实体类 /// </summary> /// <param name="assemblies">待初始化的程序集</param> public static void InitDBMap(params Assembly[] assemblies) { if (assemblies == null) { return; } lock (TableDictionary) { foreach (Assembly assembly in assemblies) { Type[] types = assembly.GetTypes(); foreach (Type type in types) { string tbName = string.Empty; DBTableAttribute attr = null; //初始化表信息 foreach (DBTableAttribute attribute in type.GetCustomAttributes(typeof(DBTableAttribute), false)) { tbName = string.IsNullOrEmpty(attribute.Name) ? type.Name : attribute.Name; attr = attribute; } //表示该类型未映射位 实体类 if (string.IsNullOrWhiteSpace(tbName)) { continue; } if (attr == null) { continue; } //所有映射表只添加一次 string tableKey = type.FullName; DBTable table = null; if (!TableDictionary.ContainsKey(tableKey)) { table = new DBTable(type, tbName, attr); TableDictionary.Add(tableKey, table); } else { table = TableDictionary[tableKey]; } } } } }
/// <summary> /// 获取实体列表 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="condition">查询条件</param> /// <returns>实体列表</returns> public virtual IList <T> GetList <T, C>(C condition) where T : new() { string sql = null; string whereSql = null; string tableName = null; Type type = null; List <DataParameter> parameters = null; DataQueryHelper queryHelper = new DataQueryHelper(); try { //设置sql工具 queryHelper.DbHelper = this.DbHelper; type = typeof(T); //获取表信息 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = this.DbHelper.GetDbObjectName(tableAtt.TableName); //构成查询语句 sql = "SELECT " + queryHelper.GetSelectColumns <T>() + " FROM " + tableName; queryHelper.GetWhere <C>(condition, out whereSql, out parameters); if (string.IsNullOrEmpty(whereSql) == false) { sql += " WHERE " + whereSql; } //获取列表 return(this.GetList <T>(sql, parameters.ToArray())); } catch (Exception ex) { this.RollbackTs(); throw ex; } finally { this.CloseCon(); } }
/// <summary> /// 获取表属性 /// </summary> private DBTableAttribute GetTableAttribute(Type t) { Type QEntity = t; //获取表明 object[] attrsClassAtt = QEntity.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt.Count() == 0) { throw new Exception("此实体无法添加到数据库请添加(DBTableAttribute)"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; return(tableAtt); }
public SqlTableDefine(DBTableAttribute tableAttr, string name) { TableAttribute = tableAttr; if (tableAttr != null) { Name = tableAttr.Name; if (string.IsNullOrEmpty(tableAttr.Name)) { Name = name; } } else { Name = name; } }
public static object InsertObject <T>(T obj) where T : TObject { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DBTableAttribute)); TStorage tStorage = new TStorage { Fields = obj.GetKeyValuePairs(), Table = dbTableAttribute.Table, PKField = obj.GetKeyField() }; TrackingServiceClient tsc = new TrackingServiceClient(); return(tsc.Insert(tStorage)); }
public static T LoadObject <T>(int id) where T : TObject { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DBTableAttribute)); TStorage tStorage = new TStorage { ID = id, Table = dbTableAttribute.Table }; TrackingServiceClient tsc = new TrackingServiceClient(); TStorage tObjStorage = tsc.LoadDetails(tStorage); var ctor = typeof(T).GetConstructor(new Type[] { }); var result = ctor.Invoke(new object[] { }) as T; result.SetKeyValuePairs(tObjStorage.Fields); return(result); }
public void Add(TMeasurement item) { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(BMeasurement), typeof(DBTableAttribute)); TStorage tStorage = new TStorage { Table = dbTableAttribute.Table, PKField = BMeasurement.KeyParm.Key, Fields = new Dictionary <string, object>() { { BMeasurement.TextParm.Key, item.Text }, { BMeasurement.DescriptionParm.Key, item.Description }, { BMeasurement.PhotoClientPathParm.Key, item.PhotoClientPath }, { BMeasurement.PhotoServerPathParm.Key, item.PhotoServerPath }, } }; Insert(tStorage); }
public static void DeleteObject <T>(T obj) where T : TObject { try { DBTableAttribute dbTableAttribute = (DBTableAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DBTableAttribute)); TStorage tStorage = new TStorage { ID = Convert.ToInt32(obj.GetKeyValue()), Table = dbTableAttribute.Table, PKField = obj.GetKeyField() }; TrackingServiceClient tsc = new TrackingServiceClient(); tsc.Delete(tStorage); } catch (Exception ex) { } }
protected BaseTM(IBaseRepository <T> repository) { DBTableAttribute attr = typeof(T).GetCustomAttribute(typeof(DBTableAttribute), true) as DBTableAttribute; if (attr != null) { _defaultSelectCommand = String.Format("Select * From {0} Where IsDeleted = 0", attr.Name); InitializeAdapter(); _adapter.DeleteCommand = new SqlCommand(String.Format("Update {0} Set IsDeleted = 1 Where Id = @Id", attr.Name)); _adapter.DeleteCommand.Parameters.Add("@Id", SqlDbType.UniqueIdentifier, 50, "Id"); } _mapper = new Dictionary <PropertyInfo, String>(); InitializeMapper(); _repository = repository; _lock = new Object(); }
/// <summary> /// 记录数据变更新信息 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="oprType">操作类型</param> /// <param name="OperateUser">操作者</param> /// <param name="oldInfo">原数据</param> /// <param name="newInfo">新数据</param> public void RecordDataChangeMark <T>(DataOprType oprType, string OperateUser, T oldInfo, T newInfo) where T : new() { string tableName = ""; DataMark mark = new DataMark(); try { Type type = typeof(T); //获取表名 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = tableAtt.TableName; //创建痕迹信息 mark.MARKID = Guid.NewGuid().ToString(); mark.OPERATEUSER = OperateUser; mark.DATAKIND = tableName; mark.OPERATETIME = DateTime.Now; mark.OPERATETYPE = oprType.ToString(); mark.DATAID = ""; mark.ORIGINALDATA = LAF.Common.Serialization.JsonConvertHelper.GetSerializes(oldInfo); if (oprType == DataOprType.Update) { mark.CHANGEDDATA = LAF.Common.Serialization.JsonConvertHelper.GetSerializes(newInfo); } //保存痕迹信息 Session.Insert <DataMark>(mark); } catch (Exception ex) { throw; } }
/// <summary> /// 获取实体类型 /// </summary> /// <param name="tableName">表名</param> /// <returns>实体类型</returns> private Type GetEntityTypeByTable(string tableName) { Type t = null; try { Assembly asse = Assembly.GetAssembly(typeof(LAF.Entity.BaseEntity)); Type[] types = asse.GetExportedTypes(); foreach (Type entityType in types) { //获取表信息 object[] attrsClassAtt = entityType.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt != null && attrsClassAtt.Length > 0) { DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; if (tableAtt.TableName == tableName) { t = entityType; break; } } } if (t == null) { throw new Exception("通过表名获取实体类型失败"); } return(t); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取实体对应数据表名称 /// </summary> /// <param name="entityName">实体名</param> /// <returns>数据表名称</returns> private string GetTableName(string entityName) { string tableName = ""; try { Type entityType = this.GetEntityType(entityName); //获取表信息 object[] attrsClassAtt = entityType.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = tableAtt.TableName; return(tableName); } catch (Exception ex) { throw ex; } }
public SqlTableDefine(DBTableAttribute tableAttr) { TableAttribute = tableAttr; Name = tableAttr.Name; }
/// <summary> /// 插入单个实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <returns>实体主键为自增时,返回主键值;否则返回插入行数。</returns> public virtual int Insert <T>(T model) where T : new() { Type type = null; string sql = ""; string tableName = ""; List <string> columns = new List <string>(); List <string> values = new List <string>(); List <DataParameter> parameters = new List <DataParameter>(); string timeStampDbColumn = ""; bool isPkIdentity = false; int r; try { type = typeof(T); //获取表信息 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = this.DbHelper.GetDbObjectName(tableAtt.TableName); PropertyInfo[] pArray = type.GetProperties(); if (string.IsNullOrEmpty(tableAtt.TimeStampColumn) == false) { //验证时间戳有效性 int timeColumnIndex = pArray.ToList().FindIndex(p => p.Name == tableAtt.TimeStampColumn); if (timeColumnIndex == -1) { throw new Exception("时间戳属性指定不正确!"); } } //获取字段信息 foreach (var item in pArray) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 //判断是否为自增 if (ca.IsIdentity == true) { if (ca.IsKey == true) { isPkIdentity = true; } continue; } string columnName = ca.ColumnName; //字段名 object value = item.GetValue(model, null); //获取值 //提取时间戳字段名 if (item.Name == tableAtt.TimeStampColumn) { timeStampDbColumn = columnName; } if (value == null) { continue; } if (ca.DataType == DbType.DateTime && value != null && (DateTime)value == new DateTime()) { value = System.DBNull.Value; } columns.Add(this.DbHelper.GetDbObjectName(columnName));//添加字段 //处理时间戳 if (string.IsNullOrEmpty(tableAtt.TimeStampColumn) == false && tableAtt.TimeStampColumn == item.Name) { values.Add(this.DbHelper.GetDateFuncName()); continue; } if (ca.DefaultValue == DataDefaultValue.None) { //添加值 values.Add(this.DbHelper.GetParameterPrefix() + columnName); //添加参数 parameters.Add(new DataParameter { ParameterName = columnName, Value = value, DataType = ca.DataType }); } else { //添加默认值 values.Add(this.GetDefaultValue(ca.DefaultValue)); } } this.OpenCon(); //执行语句 sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2}){3}" , tableName , string.Join(",", columns.ToArray()) , string.Join(",", values.ToArray()) , isPkIdentity ? ";SELECT @@IDENTITY;" : ""); //执行语句 if (isPkIdentity == true) { r = int.Parse(this.DbHelper.ExecuteScalar(sql, parameters, this.Connection, this.Transaction).ToString()); } else { r = this.DbHelper.ExecuteSql(sql, parameters, this.Connection, this.Transaction); } return(r); } catch (Exception ex) { this.RollbackTs(); throw ex; } finally { this.CloseCon(); //记录日志 this.RecordLog(sql, parameters); } }
/// <summary> /// 更新单个实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <param name="updateItems">需要更新的字段</param> /// <returns>更新行数</returns> public virtual int Update <T>(T model, List <string> updateItems) where T : new() { int count = 0; Type type = null; string sql = ""; string tableName = ""; List <string> updateColumns = new List <string>(); string whereSql = ""; List <DataParameter> parameters = null; string timeStampDbColumn = ""; try { type = typeof(T); //获取表信息 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = this.DbHelper.GetDbObjectName(tableAtt.TableName); //获取更新条件 this.GetSingleWhere <T>(model, out whereSql, out parameters); this.OpenCon(); #region 处理时间戳 if (string.IsNullOrEmpty(tableAtt.TimeStampColumn) == false) { PropertyInfo timeProperty = model.GetType().GetProperty(tableAtt.TimeStampColumn); if (timeProperty == null) { throw new Exception("时间戳属性指定不正确!"); } object[] attrs = timeProperty.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { throw new Exception("时间戳属性没有配置字段信息!"); } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 //帮段时间戳是否过期 DateTime oldTimeStamp; DateTime currentTimeStamp; timeStampDbColumn = ca.ColumnName; //获取更新实体中的时间戳 oldTimeStamp = (DateTime)BindHelper.GetPropertyValue(model, tableAtt.TimeStampColumn); //获取数据库中时间戳 sql = string.Format("select {0} from {1} where {2}", timeStampDbColumn, tableAtt.TableName, whereSql); currentTimeStamp = (DateTime)this.DbHelper.ExecuteScalar(sql, parameters, this.Connection, this.Transaction); if (oldTimeStamp.ToString() != currentTimeStamp.ToString()) { throw new Exception("时间戳过期!"); } } #endregion //获取字段属性 foreach (var item in type.GetProperties()) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 //判断主键字段或者自增字段无法更新 if (ca.IsKey == true || ca.IsIdentity == true) { continue; } //添加更新字段 if (ca.ColumnName != timeStampDbColumn) { object value = item.GetValue(model, null);//获取值 if (value == null) { value = System.DBNull.Value; } if (ca.DataType == DbType.DateTime && value != null && (DateTime)value == new DateTime()) { value = System.DBNull.Value; } //不在字段更新列表中,不进行更新 if (updateItems != null && !updateItems.Contains(ca.ColumnName)) { continue; } //普通字段 updateColumns.Add(string.Format("{0} = {1}{2}" , this.DbHelper.GetDbObjectName(ca.ColumnName), this.DbHelper.GetParameterPrefix(), ca.ColumnName)); parameters.Add(new DataParameter { ParameterName = ca.ColumnName, Value = value, DataType = ca.DataType }); //添加参数 } else { //时间戳字段 updateColumns.Add(string.Format("{0} = {1}" , this.DbHelper.GetDbObjectName(ca.ColumnName), this.DbHelper.GetDateFuncName())); } } if (string.IsNullOrEmpty(whereSql) == true) { throw new Exception("更新条件为空,实体未设置主键!"); } //构成更新语句 sql = string.Format("update {0} set {1} where {2}" , tableName, string.Join(",", updateColumns), whereSql); //执行语句 count = this.DbHelper.ExecuteSql(sql, parameters, this.Connection, this.Transaction); return(count); } catch (Exception ex) { this.RollbackTs(); throw ex; } finally { this.CloseCon(); //记录日志 this.RecordLog(sql, parameters); } }
private static Tuple <SqlTableDefine, List <SqlColumnDefine> > GetEntityDefine(Type type) { //处理表定义 var name = type.Name; DBTableAttribute tableAttr = new DBTableAttribute(""); if (EnvHelper.IsNetFX) { #if NETCOREAPP1_0 || NETSTANDARD1_6 #else tableAttr = type.GetCustomAttribute <DBTableAttribute>(); #endif } else { tableAttr = type.GetTypeInfo().GetCustomAttribute <DBTableAttribute>(); } var sqlTableDef = new SqlTableDefine(tableAttr, name); //处理列定义 var colDeflist = new List <SqlColumnDefine>(); var columns = type.GetProperties(); foreach (var cp in columns) { var ignore = cp.GetCustomAttribute <DBIgnoreAttribute>(); if (ignore == null) { var keyAttr = cp.GetCustomAttribute <DBKeyAttribute>(); var columnAttr = cp.GetCustomAttribute <DBColumnAttribute>(); var dataTypeAttr = cp.GetCustomAttribute <DBCustomeDataTypeAttribute>(); var indexAttr = cp.GetCustomAttribute <DBIndexAttribute>(); var cname = cp.Name; var alias = cname; if (columnAttr != null) { alias = columnAttr.Name; } // edit by cheery 2017-2-21 var nullable = true; // 如果是Key 不允许空 if (keyAttr != null) { nullable = false; } // 如果字段定义上有是否允许空标记 则依赖该标记 else if (columnAttr?.Nullable != null) { nullable = columnAttr.Nullable.Value; } // 否则 根据类型判断 else { nullable = cp.PropertyType.IsNullableType(); } //var nullable = keyAttr == null && (columnAttr?.Nullable ?? cp.PropertyType.IsNullableType()); var cd = new SqlColumnDefine(cname, alias, null, cp.PropertyType, nullable, columnAttr, keyAttr, dataTypeAttr, null, indexAttr); colDeflist.Add(cd); } } return(new Tuple <SqlTableDefine, List <SqlColumnDefine> >(sqlTableDef, colDeflist)); }
/// <summary> /// 获取单个实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <returns>实体数据</returns> public virtual T Get <T>(T model) where T : new() { Type type = null; string sql = ""; string tableName = ""; List <string> selectColumns = new List <string>(); string whereSql = ""; List <DataParameter> parameters = null; DataTable dt = new DataTable(); try { type = typeof(T); //获取表信息 object[] attrsClassAtt = type.GetCustomAttributes(typeof(DBTableAttribute), true); if (attrsClassAtt == null) { throw new Exception("当前实体没有添加属性DBTableAttribute!"); } DBTableAttribute tableAtt = (DBTableAttribute)attrsClassAtt[0]; tableName = this.DbHelper.GetDbObjectName(tableAtt.TableName); //获取查询条件 this.GetSingleWhere <T>(model, out whereSql, out parameters); //获取字段属性 foreach (var item in type.GetProperties()) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 selectColumns.Add(this.DbHelper.GetDbObjectName(ca.ColumnName)); } if (string.IsNullOrEmpty(whereSql) == true) { throw new Exception("获取条件为空,实体未设置主键!"); } //构成查询语句 sql = string.Format("SELECT {0} FROM {1} WHERE {2}", string.Join(",", selectColumns), tableName, whereSql); this.OpenCon(); //获取数据 this.DbHelper.FillDataTable(dt, sql, parameters, this.Connection, this.Transaction); if (dt.Rows.Count == 0) { //未检索到符合条件数据 model = default(T); } else { //检索到符合条件数据 model = ConvertToModel <T>(dt.Rows[0]); } return(model); } catch (Exception ex) { this.RollbackTs(); throw ex; } finally { this.CloseCon(); //记录日志 this.RecordLog(sql, parameters.ToList()); } }
// Checks that the table corresponding to this type exists, and if it is missing, it creates it. // Also verifies all columns represented in the class are also present in the table, creating // any missing. Needs to be enhanced to allow for changed defaults. private void verifyTable(Type tableType) { lock (lockObject) { // check that we haven't already verified this table if (isVerified.ContainsKey(tableType)) { return; } // attempt to grab table info for the type. if none exists, it's not tagged to be a table DBTableAttribute tableAttr = getDBTableAttribute(tableType); if (tableAttr == null) { return; } try { // check if the table exists in the database, if not, create it SQLiteResultSet resultSet = dbClient.Execute("select * from sqlite_master where type='table' and name = '" + tableAttr.TableName + "'"); if (resultSet.Rows.Count == 0) { resultSet = dbClient.Execute("create table " + tableAttr.TableName + " (id INTEGER primary key )"); logger.Info("Created " + tableAttr.TableName + " table."); } // grab existing table info from the DB resultSet = dbClient.Execute("PRAGMA table_info(" + tableAttr.TableName + ")"); // loop through the CLASS DEFINED fields, and verify each is contained in the result set foreach (DBField currField in DBField.GetFieldList(tableType)) { // loop through all defined columns in DB to ensure this col exists bool exists = false; foreach (SQLiteResultSet.Row currRow in resultSet.Rows) { if (currField.FieldName == currRow.fields[1]) { exists = true; break; } } // if we couldn't find the column create it if (!exists) { string defaultValue; if (currField.Default == null) { defaultValue = "NULL"; } else { defaultValue = getSQLiteString(currField, currField.Default); } dbClient.Execute("alter table " + tableAttr.TableName + " add column " + currField.FieldName + " " + currField.DBType.ToString() + " default " + defaultValue); // logger.Debug("Added " + tableAttr.TableName + "." + currField.FieldName + " column."); } } verifyRelationTables(tableType); isVerified[tableType] = true; } catch (SQLiteException e) { logger.ErrorException("Internal error verifying " + tableAttr.TableName + " (" + tableType.ToString() + ") table.", e); } } }
public SqlTableDefine(DBTableAttribute tableAttr) { TableAttribute = tableAttr; }
private void analyze(Type source) { ArrayList <DBFieldMetadata> allFields = null; ArrayList <DBFieldMetadata> identityFields = null; ArrayList <DBFieldMetadata> applicationValuedFields = null; DBFieldMetadata autoIdentityField = null; string key = createKey(source); //class fields DBTableAttribute[] atts = (DBTableAttribute[])source.GetCustomAttributes(typeof(DBTableAttribute), true); if (atts == null) { cache(key, null, null, null, null, null); return; } allFields = new ArrayList <DBFieldMetadata>(); identityFields = new ArrayList <DBFieldMetadata>(); applicationValuedFields = new ArrayList <DBFieldMetadata>(); //Class attribute DBTableAttribute classTable = atts[0]; //all fields step1 if (classTable.IdentityField != null) { allFields.put(new DBFieldMetadata(classTable, classTable.IdentityField, "Id")); } //all fields step2 PropertyInfo[] fields = source.GetProperties(); foreach (PropertyInfo field in fields) { foreach (Attribute attrib in field.GetCustomAttributes(true)) { if (attrib is DBForeignFieldAttribute) { DBForeignFieldAttribute at = (DBForeignFieldAttribute)attrib; allFields.put(new DBFieldMetadata(classTable, at, field.Name, field.Name + "." + at.PropertyPath)); } else if (attrib is DBFieldAttribute) { allFields.put(new DBFieldMetadata(classTable, (DBFieldAttribute)attrib, field.Name)); } } } //parse all fields for identity fields for (int i = 0; i < allFields.Count - 1; i++) { if ((allFields[i].IsIdentityFull) || (allFields[i].IsIdentityPart)) { identityFields.put(allFields[i]); } } //parse all fields for application valued fields for (int i = 0; i < allFields.Count; i++) { if (allFields[i].ValueGeneration == DBFieldValueGenerationEnum.Application) { applicationValuedFields.put(allFields[i]); } } //parse identities for auto for (int i = 0; i < identityFields.Count; i++) { if (identityFields[i].ValueGeneration == DBFieldValueGenerationEnum.Auto) { autoIdentityField = identityFields[i]; break; } } cache(key, allFields.toArray(), identityFields.toArray(), applicationValuedFields.toArray(), autoIdentityField, classTable); }