public SqlColumnDefine(DBColumnAttribute columnAttribute, DBKeyAttribute keyAttribute = null) { Name = columnAttribute.Name; AliasName = columnAttribute.Name; ColumnAttribute = columnAttribute; KeyAttribute = keyAttribute; }
public SqlColumnDefine(DBColumnAttribute columnAttribute, DBKeyAttribute keyAttribute = null, DBIndexAttribute indexAttr = null) { Name = columnAttribute.Name; AliasName = columnAttribute.Name; ColumnAttribute = columnAttribute; KeyAttribute = keyAttribute; IndexAttribute = indexAttr; }
/// <summary> /// 获取唯一记录查询条件 /// </summary> public virtual void GetSingleWhere <T>(T model, out string whereSql, out List <DataParameter> parameters) { Type type = null; StringBuilder sBuilder = new StringBuilder(); try { //初始化 whereSql = ""; parameters = new List <DataParameter>(); type = typeof(T); //获取字段信息 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 == false) { continue; } //添加条件 sBuilder.Append(string.Format(" and {0} = {1}{2}" , this.DbHelper.GetDbObjectName(ca.ColumnName), this.DbHelper.GetParameterPrefix(), ca.ColumnName)); //获取值 object value = item.GetValue(model, null); //添加参数 parameters.Add(new DataParameter { ParameterName = ca.ColumnName, Value = value, DataType = ca.DataType }); } whereSql = sBuilder.ToString(); if (whereSql != "") { whereSql = whereSql.Substring(4); } } catch (Exception ex) { throw ex; } }
/// <summary> /// 这个方法可以在sql拼接中使用,把model中的映射字段替换成特性的字段名 /// </summary> /// <param name="property"></param> /// <returns></returns> public static string GetColumnName(this PropertyInfo property) { if (property.IsDefined(typeof(DBColumnAttribute), true)) { DBColumnAttribute attribute = (DBColumnAttribute)property.GetCustomAttribute(typeof(DBColumnAttribute), true); return(attribute.GetColumnName()); } else { return(property.Name); } }
public SqlColumnDefine(string name, string aliasName, object value, Type valueType, bool nullAble, DBColumnAttribute columnAttr, DBKeyAttribute keyAttr, DBCustomeDataTypeAttribute customeDataTypeAttr, DBIgnoreAttribute ignoreAttr = null) { Name = name; AliasName = aliasName; Value = value; ColumnAttribute = columnAttr; KeyAttribute = keyAttr; DataTypeAttribute = customeDataTypeAttr; IgnoreAttribute = ignoreAttr; ValueType = valueType; NullAble = nullAble; }
private void Init(string name, string aliasName, object value, Type valueType, bool nullAble, DBColumnAttribute columnAttr, DBKeyAttribute keyAttr, DBCustomeDataTypeAttribute customeDataTypeAttr, DBIgnoreAttribute ignoreAttr, DBIndexAttribute indexAttr) { Name = name; AliasName = aliasName; Value = value; ColumnAttribute = columnAttr; KeyAttribute = keyAttr; DataTypeAttribute = customeDataTypeAttr; IgnoreAttribute = ignoreAttr; ValueType = valueType; NullAble = nullAble; IndexAttribute = indexAttr; }
/// <summary> /// 将数据行转换成实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="row">数据行</param> /// <returns>实体</returns> public static T ConvertToModel <T>(DataRow row) where T : new() { //判断行是否为空 if (row == null) { return(default(T)); } T model = new T(); PropertyInfo[] properties = model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); //赋值 foreach (PropertyInfo p in properties) { object[] attrs = p.GetCustomAttributes(typeof(DBColumnAttribute), true); string colName = ""; if (attrs.Count() == 0) { if (row.Table.Columns.IndexOf(p.Name) < 0) { continue; } colName = p.Name; } else { DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 if (row.Table.Columns.IndexOf(ca.ColumnName) < 0) { continue; } colName = ca.ColumnName; } if (!(row[colName] is DBNull)) { p.SetValue(model, ChangeType(row[colName], p.PropertyType), null); } } return(model); }
///// <summary> ///// 获取查询字段 ///// </summary> ///// <returns></returns> //private string ToSelectString() //{ // List<string> strSelect = new List<string>(); // Type QEntity = typeof(TModel); // string _FieldName = string.Empty; // //获取字段 // foreach (var item in QEntity.GetProperties()) // { // object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); // var columnItem = string.Empty; // if (attrs.Count() > 0) // { // DBColumnAttribute temp = (DBColumnAttribute)attrs[0]; // columnItem = temp.ColumnName; // } // if (!string.IsNullOrEmpty(columnItem)) // { // strSelect.Add(columnItem); // } // } // return string.Join(",", strSelect.ToArray()); //} #endregion #region 获取主键信息 /// <summary> /// 获取主键信息 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <returns>主键信息</returns> public Dictionary <string, object> GetPkColumns <T>(T model) where T : new() { Dictionary <string, object> pkColumns = new Dictionary <string, object>(); try { Type modelType = typeof(T); //获取字段属性 foreach (var item in modelType.GetProperties()) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 if (ca.IsKey == true) { object value = item.GetValue(model, null);//获取值 if (this.DbHelper != null) { pkColumns.Add(this.DbHelper.GetDbObjectName(ca.ColumnName), value); } else { pkColumns.Add(ca.ColumnName, value); } } } return(pkColumns); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取查询字段 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <returns>以逗号间隔的查询字段</returns> public string GetSelectColumns <T>() where T : new() { List <string> columns = new List <string>(); Type modelType = null; try { modelType = typeof(T); //获取字段属性 foreach (var item in modelType.GetProperties()) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 if (this.DbHelper != null) { columns.Add(this.DbHelper.GetDbObjectName(ca.ColumnName)); } else { columns.Add(ca.ColumnName); } } return(string.Join(",", columns.ToArray())); } catch (Exception ex) { throw ex; } }
public DataMark GetInfo(DataMark info) { DataTable columnDt = new DataTable(); object oldInfo = null; object newInfo = null; Type entityType; try { //获取数据 info = new DataChangeManageDAL().GetInfo(info, ref columnDt); //获取实体类型 entityType = this.GetEntityTypeByTable(info.DATAKIND); info.DATAKIND = info.DATAKINDDES; //json格式数据转换为实体 if (string.IsNullOrEmpty(info.ORIGINALDATA) == false) { oldInfo = JsonConvertHelper.GetDeserialize(entityType, info.ORIGINALDATA); } if (string.IsNullOrEmpty(info.CHANGEDDATA) == false) { newInfo = JsonConvertHelper.GetDeserialize(entityType, info.CHANGEDDATA); } //生成字段明细数据 PropertyInfo[] pArray = entityType.GetProperties(); info.Details = new List <DataMarkDetail>(); //获取字段信息 foreach (var item in pArray) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 DataMarkDetail detail = new DataMarkDetail(); //原值 object oldValue = null; if (oldInfo != null) { oldValue = BindHelper.GetPropertyValue(oldInfo, item.Name); } detail.OldValue = oldValue == null?"":oldValue.ToString(); //变更后值 object newValue = null; if (newInfo != null) { newValue = BindHelper.GetPropertyValue(newInfo, item.Name); } detail.NewValue = newValue == null ? "" : newValue.ToString(); DataRow[] rows = columnDt.Select("COLUMNNAME='" + ca.ColumnName + "'"); if (rows.Length > 0) { detail.ColumnDes = rows[0]["COLUMNDES"].ToString(); } if (string.IsNullOrEmpty(detail.ColumnDes) == true) { continue; } info.Details.Add(detail); } return(info); } catch (Exception ex) { throw ex; } }
public DataGridViewEvents(DataGridView control) { dgv = control; string HeaderText; var query = AppDatabase.database.Table <T>(); foreach (var stock in query) { bindingSource.Add(stock); } dgv.AutoGenerateColumns = false; //dgv.AutoSize = true; dgv.DataSource = bindingSource; dgv.CellContentClick += dgvWorkTypes_CellContentClick; dgv.CellEndEdit += dgvWorkTypes_CellEndEdit; dgv.DataError += Dgv_DataError; PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo property in properties) { if (new List <string> { "id", "_id", "_name" }.Contains(property.Name)) { continue; } object[] attrs = property.GetCustomAttributes(true); HeaderText = getDisplayName(property.Name, attrs); if (property.PropertyType.IsEnum) { DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn { DataSource = Enum.GetValues(property.PropertyType) .Cast <Enum>() .Select(value => new { (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description, value }) .OrderBy(item => item.value) .ToList(), DataPropertyName = property.Name, HeaderText = HeaderText, DisplayMember = "Description", ValueMember = "value" }; dgv.Columns.Add(combo); } else if (property.PropertyType.IsPrimitive && isDBColumnAttribute(attrs)) { DBColumnAttribute tblName = getDBColumnAttribute(attrs); HeaderText = getDisplayName(property.Name, attrs); TableMapping map = new TableMapping(tblName.tableType); //thanks to https://answers.unity.com/questions/841093/passing-type-variable-to-generic-type-variable-not.html MethodInfo genericFunction = AppDatabase.database.GetType().GetMethod("Table"); MethodInfo realFunction = genericFunction.MakeGenericMethod(tblName.tableType); dynamic query2 = realFunction.Invoke(AppDatabase.database, new object[] { }); List <BaseModel> items = new List <BaseModel>(); foreach (BaseModel stock in query2) { var x = Activator.CreateInstance(tblName.tableType); x = stock; items.Add((BaseModel)x); } DataGridViewComboBoxColumn combo = new ExtendedDataGridViewComboBoxColumn { DataSource = items, propertyName = property.Name, HeaderText = HeaderText, DisplayMember = "_name", ValueMember = "_id", ValueType = typeof(int), DataPropertyName = property.Name, }; dgv.Columns.Add(combo); } else if (property.PropertyType.IsPrimitive) { DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn { DataPropertyName = property.Name, HeaderText = HeaderText, ValueType = property.GetType(), }; dgv.Columns.Add(column); } else if (property.PropertyType == typeof(string)) { DataGridViewTextBoxColumn combo = new DataGridViewTextBoxColumn { HeaderText = HeaderText, ValueType = typeof(string), DataPropertyName = property.Name, }; dgv.Columns.Add(combo); } else if (property.PropertyType == typeof(DateTime)) { DataGridViewTextBoxColumn combo = new DataGridViewTextBoxColumn { HeaderText = HeaderText, ValueType = typeof(DateTime), DataPropertyName = property.Name, }; combo.DefaultCellStyle.Format = "MM/dd/yyyy"; dgv.Columns.Add(combo); } } DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn { HeaderText = "حذف", Text = "حذف", UseColumnTextForButtonValue = true }; dgv.Columns.Add(btnColumn); }
/// <summary> /// 获取查询条件 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="model">实体</param> /// <param name="parameters">查询参数</param> /// <returns>查询条件</returns> public void GetWhere <T>(T model, out string whereSql, out List <DataParameter> parameters) { Type type = null; StringBuilder whereBuilder = new StringBuilder(); try { //初始化 whereSql = ""; parameters = new List <DataParameter>(); type = typeof(T); //构成条件 foreach (var item in type.GetProperties()) { object[] attrs = item.GetCustomAttributes(typeof(DBColumnAttribute), true); if (attrs.Count() == 0) { continue; } //字段属性 DBColumnAttribute ca = (DBColumnAttribute)attrs[0]; //获取值 object value = item.GetValue(model, null); if (value == null) { continue; } if (value.GetType().ToString() == "System.DateTime" && ((DateTime)value == new DateTime() || value.ToString().Substring(0, 4) == "0001")) { continue; } if (this.DbHelper != null) { whereBuilder.Append(string.Format(" and {0} = {1}{2}" , this.DbHelper.GetDbObjectName(ca.ColumnName) , this.DbHelper.GetParameterPrefix() , ca.ColumnName)); } else { whereBuilder.Append(string.Format(" and {0} = {1}{2}" , ca.ColumnName, "@", ca.ColumnName)); } parameters.Add(new DataParameter { ParameterName = ca.ColumnName, Value = value, DataType = ca.DataType }); } whereSql = whereBuilder.ToString(); if (whereSql != "") { whereSql = whereSql.Substring(4); } } catch (Exception ex) { throw ex; } }
/// <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); } }
/// <summary> /// 将数据表转换为实体列表 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="table">数据表</param> /// <returns>实体列表</returns> public static IList <T> ConvertToList <T>(DataTable table) where T : new() { IList <T> list = new List <T>(); T model = new T(); PropertyInfo[] properties = model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); Dictionary <string, string> cols = new Dictionary <string, string>(); //获取属性-字段对应关系 foreach (PropertyInfo p in properties) { object[] attrs = p.GetCustomAttributes(typeof(DBColumnAttribute), true); string colName = ""; if (attrs.Count() == 0) { if (table.Columns.IndexOf(p.Name) < 0) { continue; } colName = p.Name; } else { DBColumnAttribute ca = (DBColumnAttribute)attrs[0];//字段属性 if (table.Columns.IndexOf(ca.ColumnName) < 0) { continue; } colName = ca.ColumnName; } cols.Add(p.Name, colName); } //绑定数据 foreach (DataRow row in table.Rows) { T e = new T(); foreach (PropertyInfo p in properties) { if (cols.ContainsKey(p.Name) == false) { continue; } string colName = cols[p.Name]; if (!(row[colName] is DBNull)) { p.SetValue(e, ChangeType(row[colName], p.PropertyType), null); } } list.Add(e); } return(list); }
public SqlColumnDefine(string name, string aliasName, object value, Type valueType, bool nullAble, DBColumnAttribute columnAttr, DBKeyAttribute keyAttr, DBCustomeDataTypeAttribute customeDataTypeAttr, DBIgnoreAttribute ignoreAttr = null, DBIndexAttribute indexAttr = null) { Init(name, aliasName, value, valueType, nullAble, columnAttr, keyAttr, customeDataTypeAttr, ignoreAttr, indexAttr); }
public static void AddParameter <T>(this SqlCommand command, string name, DBColumnAttribute attribute, T value) { command.AddParameter(name, attribute.DbType, attribute.Size, value); }
private void InitBindings() { ColumnBindings = new Dictionary <DBMemberInfo, DBColumnInfo>(); List <MemberInfo> members = new List <MemberInfo>(ClassType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)); members.AddRange(ClassType.GetProperties()); foreach (MemberInfo memberInfo in members) { object[] attributes = memberInfo.GetCustomAttributes(typeof(DBColumnAttribute), false); switch (attributes.Length) { case 0: break; case 1: { DBColumnAttribute dbAttribute = (DBColumnAttribute)attributes[0]; string bindingName = dbAttribute.CustomBindingName ?? memberInfo.Name; Type bindingType; switch (memberInfo.MemberType) { case MemberTypes.Field: { FieldInfo fieldInfo = (FieldInfo)memberInfo; bindingType = ((FieldInfo)memberInfo).FieldType; break; } case MemberTypes.Property: { PropertyInfo propertyInfo = (PropertyInfo)memberInfo; bindingType = propertyInfo.PropertyType; break; } default: throw new Exception("Can save to database only fields and properties"); } if (DatabaseManager.IsTypeSupported(bindingType)) { ColumnBindings.Add(new DBMemberInfo(memberInfo), new DBColumnInfo(bindingName, bindingType)); } else { throw new DBStorageException(string.Format("This storage can not store value of type {0} of '{1}", bindingType, memberInfo.Name)); } break; } default: throw new Exception(string.Format("Only one <DBColumnAttribute> attribute is allowed, got {0}", attributes.Length)); } } }
/// <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()); } }
public SqlColumnDefine(DBColumnAttribute columnAttribute, DBKeyAttribute keyAttribute = null, DBIndexAttribute indexAttr = null) { Init(columnAttribute.Name, columnAttribute.Name, null, columnAttribute.ValueType, columnAttribute.Nullable.HasValue ? columnAttribute.Nullable.Value : false, columnAttribute, keyAttribute, null, null, indexAttr); }
/// <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); } }