public static void Ctor_Default() { ColumnAttribute attribute = new ColumnAttribute(); Assert.Null(attribute.Name); Assert.Equal(-1, attribute.Order); Assert.Null(attribute.TypeName); }
public static void Ctor_String(string name) { ColumnAttribute attribute = new ColumnAttribute(name); Assert.Equal(name, attribute.Name); Assert.Equal(-1, attribute.Order); Assert.Null(attribute.TypeName); }
protected override void CreateColumnMap(Type entityType, MemberInfo member, ColumnAttribute columnAtt, ColumnMapCollection columnMaps) { if (ColumnPredicate(member)) { // Map public property to DB column columnMaps.Add(new ColumnMap(member)); } }
/// <summary> /// Registers any member with a ColumnAttribute as a ColumnMap. /// <param name="entityType">The entity that is being mapped.</param> /// <param name="member">The current member that is being inspected.</param> /// <param name="columnAtt">A ColumnAttribute (is null of one does not exist).</param> /// <param name="columnMaps">A list of ColumnMaps.</param> /// </summary> protected override void CreateColumnMap(Type entityType, MemberInfo member, ColumnAttribute columnAtt, ColumnMapCollection columnMaps) { if (columnAtt != null) { ColumnMap columnMap = new ColumnMap(member, columnAtt); columnMaps.Add(columnMap); } }
/// <summary> /// Maps properties to DB columns if a ColumnAttribute is not present. /// <param name="entityType">The entity that is being mapped.</param> /// <param name="member">The current member that is being inspected.</param> /// <param name="columnAtt">A ColumnAttribute (is null of one does not exist).</param> /// <param name="columnMaps">A list of ColumnMaps.</param> /// </summary> protected override void CreateColumnMap(Type entityType, MemberInfo member, ColumnAttribute columnAtt, ColumnMapCollection columnMaps) { if (columnAtt != null) { // Add columns with ColumnAttribute base.CreateColumnMap(entityType, member, columnAtt, columnMaps); } else { if (member.MemberType == MemberTypes.Property) { // Map public property to DB column columnMaps.Add(new ColumnMap(member)); } } }
public static void Order_Set_NegativeValue_ThrowsArgumentOutOfRangeException() { ColumnAttribute attribute = new ColumnAttribute(); AssertExtensions.Throws <ArgumentOutOfRangeException>("value", () => attribute.Order = -1); }
internal static SqlType Get(Type memberType, ColumnAttribute col) { SqlType result = null; DBType dbType = col.DbType; string key = null; if (col.DbType == DBType.Unkonw) { var typeKey = memberType.TypeHandle.Value.GetHashCode(); if (col.Length == 0 && col.IsNullable && col.Precision == 0 && col.Scale == 0) { if (defaultTypes.TryGetValue(typeKey, out result)) { return(result); } } var underlyingType = memberType; if (underlyingType.IsNullable()) { underlyingType = Nullable.GetUnderlyingType(underlyingType); } if (underlyingType.IsEnum) { underlyingType = Enum.GetUnderlyingType(underlyingType); } //if (!TypeMap.TryGetValue(underlyingType.TypeHandle.Value.GetHashCode(), out dbType)) // throw new NotSupportedException("Not support '" + underlyingType.FullName + "' for field or property type."); typeKey = underlyingType.TypeHandle.Value.GetHashCode(); if (TypeMap.TryGetValue(typeKey, out dbType)) { key = string.Concat(typeKey, col.Length, col.IsNullable, col.Precision, col.Scale); if (SqlTypes.TryGetValue(key, out result)) { return(result); } defaultTypes.TryGetValue(typeKey, out result); } } else { key = string.Concat(col.DbType, col.Length, col.IsNullable, col.Precision, col.Scale); if (SqlTypes.TryGetValue(key, out result)) { return(result); } result = new SqlType(col.DbType); } if (result != null) { dbType = result.DbType; } result = new SqlType(dbType, col.Precision, col.Scale) { Length = col.Length, Required = !col.IsNullable }; lock (SqlTypes) SqlTypes.Add(key, result); return(result); }
private void DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false) { if (recordType == null) { return; } if (!recordType.IsDynamicType()) { Type pt = null; if (optIn) //ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType<ChoKVPRecordFieldAttribute>().Any()).Any()) { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { pt = pd.PropertyType.GetUnderlyingType(); if (!pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt)) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn); } else if (pd.Attributes.OfType <ChoKVPRecordFieldAttribute>().Any()) { var obj = new ChoKVPRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoKVPRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray()); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); if (!KVPRecordFieldConfigurations.Any(c => c.Name == pd.Name)) { KVPRecordFieldConfigurations.Add(obj); } } } } else { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { pt = pd.PropertyType.GetUnderlyingType(); if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt)) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn); } else { var obj = new ChoKVPRecordFieldConfiguration(pd.Name); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault(); if (slAttr != null && slAttr.MaximumLength > 0) { obj.Size = slAttr.MaximumLength; } DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault(); if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace()) { obj.FieldName = dnAttr.DisplayName.Trim(); } else { DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (dpAttr != null) { if (!dpAttr.ShortName.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.ShortName; } else if (!dpAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.Name; } obj.Order = dpAttr.Order; } else { ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault(); if (clAttr != null) { obj.Order = clAttr.Order; if (!clAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = clAttr.Name; } } } } DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault(); if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace()) { obj.FormatText = dfAttr.DataFormatString; } if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace()) { obj.NullValue = dfAttr.NullDisplayText; } if (!KVPRecordFieldConfigurations.Any(c => c.Name == pd.Name)) { KVPRecordFieldConfigurations.Add(obj); } } } } } }
private void DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false) { if (recordType == null) { return; } if (!recordType.IsDynamicType()) { IsComplexXPathUsed = false; Type pt = null; if (optIn) //ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType<ChoXmlNodeRecordFieldAttribute>().Any()).Any()) { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { pt = pd.PropertyType.GetUnderlyingType(); var fa = pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().FirstOrDefault(); bool optIn1 = fa == null || fa.UseXmlSerialization ? optIn : ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()).Any(); if (false) //optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt)) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1); } else if (pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()) { bool useCache = true; string xpath = null; ChoXmlNodeRecordFieldAttribute attr = ChoTypeDescriptor.GetPropetyAttribute <ChoXmlNodeRecordFieldAttribute>(pd); if (attr.XPath.IsNullOrEmpty()) { if (!attr.FieldName.IsNullOrWhiteSpace()) { attr.XPath = $"/{attr.FieldName}|/@{attr.FieldName}"; } else { attr.XPath = xpath = $"/{pd.Name}|/@{pd.Name}"; } IsComplexXPathUsed = true; } else { useCache = false; } var obj = new ChoXmlRecordFieldConfiguration(pd.Name, attr, pd.Attributes.OfType <Attribute>().ToArray()); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); obj.UseCache = useCache; if (obj.XPath.IsNullOrWhiteSpace()) { if (!obj.FieldName.IsNullOrWhiteSpace()) { obj.XPath = $"/{obj.FieldName}|/@{obj.FieldName}"; } else { obj.XPath = $"/{obj.Name}|/@{obj.Name}"; } } obj.FieldType = pd.PropertyType.GetUnderlyingType(); if (!XmlRecordFieldConfigurations.Any(c => c.Name == pd.Name)) { XmlRecordFieldConfigurations.Add(obj); } } } } else { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { XmlIgnoreAttribute xiAttr = pd.Attributes.OfType <XmlIgnoreAttribute>().FirstOrDefault(); if (xiAttr != null) { continue; } pt = pd.PropertyType.GetUnderlyingType(); if (false) //pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt)) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn); } else { var obj = new ChoXmlRecordFieldConfiguration(pd.Name, $"/{pd.Name}|/@{pd.Name}"); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault(); if (slAttr != null && slAttr.MaximumLength > 0) { obj.Size = slAttr.MaximumLength; } XmlElementAttribute xAttr = pd.Attributes.OfType <XmlElementAttribute>().FirstOrDefault(); if (xAttr != null && !xAttr.ElementName.IsNullOrWhiteSpace()) { obj.FieldName = xAttr.ElementName; } else { XmlAttributeAttribute xaAttr = pd.Attributes.OfType <XmlAttributeAttribute>().FirstOrDefault(); if (xAttr != null && !xaAttr.AttributeName.IsNullOrWhiteSpace()) { obj.FieldName = xaAttr.AttributeName; } else { DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault(); if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace()) { obj.FieldName = dnAttr.DisplayName.Trim(); } else { DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (dpAttr != null) { if (!dpAttr.ShortName.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.ShortName; } else if (!dpAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.Name; } obj.Order = dpAttr.Order; } else { ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault(); if (clAttr != null) { obj.Order = clAttr.Order; if (!clAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = clAttr.Name; } } } } } } DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault(); if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace()) { obj.FormatText = dfAttr.DataFormatString; } if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace()) { obj.NullValue = dfAttr.NullDisplayText; } if (!XmlRecordFieldConfigurations.Any(c => c.Name == pd.Name)) { XmlRecordFieldConfigurations.Add(obj); } } } } } }
/// <summary> /// 创建 INSRT 命令 /// </summary> /// <param name="tree">查询语义</param> /// <param name="context">解析SQL命令上下文</param> /// <returns></returns> protected override DbRawCommand TranslateInsertCommand <T>(DbQueryInsertTree tree, ITranslateContext context) { ISqlBuilder builder = this.CreateSqlBuilder(context);; var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo <T>(); if (tree.Entity != null) { // 如果没有Sequence列,使用 INSERT ALL INTO 语法,否则就一条一条逐行写入~~ // 批量 INSERT,自增列不会自动赋值 object entity = tree.Entity; ISqlBuilder columnsBuilder = this.CreateSqlBuilder(context); ISqlBuilder valuesBuilder = this.CreateSqlBuilder(context); // 指定插入列 var members = typeRuntime.Members; if (tree.EntityColumns != null && tree.EntityColumns.Count > 0) { members = new MemberAccessorCollection(); for (int i = 0; i < tree.EntityColumns.Count; i++) { Expression curExpr = tree.EntityColumns[i]; if (curExpr.NodeType == ExpressionType.Lambda) { curExpr = (curExpr as LambdaExpression).Body.ReduceUnary(); } if (curExpr.NodeType != ExpressionType.MemberAccess) { throw new XFrameworkException("Can't read field name from expression {0}", tree.EntityColumns[i]); } MemberExpression member = curExpr as MemberExpression; string name = member.Member.Name; members[name] = typeRuntime.Members[name]; } } // 自增列参数 IDbDataParameter seqParameter = null; // 自增列标记 ColumnAttribute seqColumn = null; foreach (var item in members) { var m = item as FieldAccessorBase; if (m == null || !m.IsDbField) { continue; } columnsBuilder.AppendMember(null, m.Member, typeRuntime.Type); columnsBuilder.Append(','); if (m == typeRuntime.Identity) { seqColumn = m.Column; if (tree.Bulk == null) { // 非批量INSERT,产生一个 OUTPUT 类型的参数 string parameterName = string.Format("{0}{1}{2}", this.ParameterPrefix, AppConst.PARAMETER_NAME_PRIFIX, context.Parameters.Count); seqParameter = this.DbProvider.CreateParameter(parameterName, -1, direction: ParameterDirection.Output); context.Parameters.Add(seqParameter); valuesBuilder.Append(seqParameter.ParameterName); valuesBuilder.Append(','); } else { valuesBuilder.AppendMember(((OracleColumnAttribute)m.Column).SEQName); valuesBuilder.Append(".NEXTVAL"); valuesBuilder.Append(','); } } else { var value = m.Invoke(entity); string sqlExpression = this.Constor.GetSqlValueWidthDefault(value, context, m.Column); valuesBuilder.Append(sqlExpression); valuesBuilder.Append(','); } } columnsBuilder.Length -= 1; valuesBuilder.Length -= 1; if (tree.Bulk == null) { // 非批量INSERT,产生一个 OUTPUT 类型的参数 if (seqParameter != null) { seqParameter.Direction = ParameterDirection.Output; seqParameter.DbType = DbType.Int64; builder.Append("SELECT "); builder.AppendMember(((OracleColumnAttribute)seqColumn).SEQName); builder.Append(".NEXTVAL INTO "); builder.Append(seqParameter.ParameterName); builder.Append(" FROM DUAL;"); builder.AppendNewLine(); //useSEQ = true; } builder.Append("INSERT "); } else { // 批量 INSERT if (!tree.Bulk.OnlyValue || seqColumn != null) { builder.Append("INSERT "); } // 如果有自增列则不使用 INSERT ALL INTO 语法 if (!tree.Bulk.OnlyValue && seqColumn == null) { builder.Append("ALL "); } } builder.Append("INTO "); builder.AppendTable(typeRuntime.TableSchema, typeRuntime.TableName, typeRuntime.IsTemporary); builder.Append('('); builder.Append(columnsBuilder); builder.Append(')'); builder.AppendNewLine(); builder.AppendTab(); builder.Append("VALUES"); builder.Append('('); builder.Append(valuesBuilder); builder.Append(')'); if (tree.Bulk == null) { builder.Append(';'); } else { if (seqColumn != null) { if (tree.Bulk.IsEndPos) { builder.Append(";"); } else { builder.AppendNewLine(";"); } } else { builder.AppendNewLine(); if (tree.Bulk.IsEndPos) { builder.Append("SELECT 1 FROM DUAL;"); } } } } else if (tree.Select != null) { builder.Append("INSERT INTO "); builder.AppendTable(typeRuntime.TableSchema, typeRuntime.TableName, typeRuntime.IsTemporary); builder.Append('('); var srcExpressionType = context.CurrentExpressionType; var srcIsOutermost = context.CurrentIsOutermost; context.CurrentExpressionType = DbExpressionType.Insert; context.CurrentIsOutermost = false; var cmd = this.TranslateSelectCommand(tree.Select, 0, false, context) as DbSelectCommand; context.CurrentExpressionType = srcExpressionType; context.CurrentIsOutermost = srcIsOutermost; int index = 0; foreach (var column in cmd.SelectedColumns) { builder.AppendMember(column.Name); if (index < cmd.SelectedColumns.Count - 1) { builder.Append(','); } index++; } builder.Append(')'); builder.AppendNewLine(); builder.Append(cmd.CommandText); builder.Append(';'); } var result = new DbRawCommand(builder.ToString(), builder.TranslateContext != null ? builder.TranslateContext.Parameters : null, System.Data.CommandType.Text); return(result); }
/// <summary> /// Initializes a new instance of the <see cref="SqlTypeInfo"/> class. /// </summary> /// <param name="type">The table type.</param> /// <param name="adapter">The adapter used to generate SQL commands.</param> public SqlTypeInfo(Type type, ISqlAdapter adapter) { Type = type; Adapter = adapter ?? SqlAdapter.GetAdapter(ExtraCrud.Dialect); TableAttribute tableAttr = type.GetCustomAttribute <TableAttribute>(false); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.NonPublic; // Determine the TableName, Adapter, and BindingFlags bool inherit = false; if (tableAttr == null) { var tableAttr2 = type.GetCustomAttribute <System.ComponentModel.DataAnnotations.Schema.TableAttribute>(false); if (tableAttr2 != null && !string.IsNullOrWhiteSpace(tableAttr2.Schema)) { TableName = tableAttr2.Name; if (!string.IsNullOrWhiteSpace(tableAttr2.Schema)) { Schema = tableAttr2.Schema.Trim(); } } else { TableName = type.Name; } } else { TableName = string.IsNullOrWhiteSpace(tableAttr.Name) ? type.Name : tableAttr.Name; if (tableAttr.DeclaredOnly) { flags |= BindingFlags.DeclaredOnly; Attributes |= SqlTableAttributes.DeclaredOnly; } if (tableAttr.InheritAttributes) { inherit = true; Attributes |= SqlTableAttributes.InheritAttributes; } if (!string.IsNullOrWhiteSpace(tableAttr.Schema)) { Schema = tableAttr.Schema.Trim(); } } FullyQualifiedTableName = TableName; if (Schema != null) { FullyQualifiedTableName = Schema + "." + TableName; } // Filter properties and iterate them for primary keys PropertyInfo[] properties = type.GetProperties(flags); PropertyInfo[] validProperties = properties.Where(ExtraCrud.IsValidProperty).Where(prop => { return(prop.GetCustomAttribute <NotMappedAttribute>(inherit) == null && prop.GetCustomAttribute <System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute>(inherit) == null); }).ToArray(); if (!validProperties.Any()) { throw new InvalidOperationException(type.FullName + " does not have any valid properties."); } ReadOnlyAttribute readOnlyAttr = type.GetCustomAttribute <ReadOnlyAttribute>(false); if (readOnlyAttr != null) { Attributes |= SqlTableAttributes.IgnoreInsert | SqlTableAttributes.IgnoreUpdate | SqlTableAttributes.IgnoreDelete; } else { var editableAttr = type.GetCustomAttribute <System.ComponentModel.DataAnnotations.EditableAttribute>(false); AutoSyncAttribute autoSyncAttr = type.GetCustomAttribute <AutoSyncAttribute>(false); if (autoSyncAttr != null) { if (autoSyncAttr.SyncUpdate) { Attributes |= SqlTableAttributes.UpdateAutoSync; } if (autoSyncAttr.SyncInsert) { Attributes |= SqlTableAttributes.InsertAutoSync; } } if (editableAttr != null) { if (!editableAttr.AllowEdit) { Attributes |= SqlTableAttributes.IgnoreUpdate; } if (editableAttr.AllowInitialValue) { Attributes |= SqlTableAttributes.IgnoreInsert; } } else { IgnoreInsertAttribute noInserts = type.GetCustomAttribute <IgnoreInsertAttribute>(false); if (noInserts != null) { Attributes |= SqlTableAttributes.IgnoreInsert; } IgnoreUpdateAttribute noUpdates = type.GetCustomAttribute <IgnoreUpdateAttribute>(false); if (noUpdates != null) { Attributes |= SqlTableAttributes.IgnoreUpdate; } } IgnoreDeleteAttribute noDeletes = type.GetCustomAttribute <IgnoreDeleteAttribute>(false); if (noDeletes != null) { Attributes |= SqlTableAttributes.IgnoreDelete; } } // Determine primary key List <SqlColumn> keys = new List <SqlColumn>(); List <SqlColumn> columns = new List <SqlColumn>(); int autoKeyCount = 0; for (int i = 0; i < validProperties.Length; i++) { PropertyInfo prop = validProperties[i]; string columnName = null; ColumnAttribute columnAttr = prop.GetCustomAttribute <ColumnAttribute>(inherit); if (columnAttr != null) { columnName = columnAttr.Name; } else { var columnAttr2 = prop.GetCustomAttribute <System.ComponentModel.DataAnnotations.Schema.ColumnAttribute>(inherit); if (columnAttr2 != null) { columnName = columnAttr2.Name; } } string propName = Adapter.QuoteIdentifier(prop.Name); SqlColumn column = new SqlColumn(prop, string.IsNullOrWhiteSpace(columnName) ? propName : Adapter.QuoteIdentifier(columnName), propName, i); KeyAttribute keyAttr = prop.GetCustomAttribute <KeyAttribute>(inherit); if (keyAttr != null) { if (keyAttr.AutoIncrement) { autoKeyCount++; } column.Attributes = keyAttr.AutoIncrement ? SqlColumnAttributes.AutoKey : SqlColumnAttributes.Key; } else { var keyAttrCm = prop.GetCustomAttribute <System.ComponentModel.DataAnnotations.KeyAttribute>(inherit); if (keyAttrCm != null) { var requiredAttr = prop.GetCustomAttribute <System.ComponentModel.DataAnnotations.RequiredAttribute>(inherit); if (requiredAttr != null && ExtraCrud.IsValidAutoIncrementType(prop.PropertyType)) { column.Attributes |= SqlColumnAttributes.Key; } else { column.Attributes |= SqlColumnAttributes.AutoKey; autoKeyCount++; } } } if (column.IsKey) { keys.Add(column); if (!prop.CanRead || !prop.GetMethod.IsPublic || prop.GetMethod.IsStatic) { Attributes |= SqlTableAttributes.IgnoreInsert | SqlTableAttributes.IgnoreUpdate | SqlTableAttributes.IgnoreDelete; } } columns.Add(column); } if (keys.Count == 0) { string quotedId = Adapter.QuoteIdentifier("ID"); SqlColumn key = columns.FirstOrDefault(c => string.Equals(c.ColumnName, quotedId, StringComparison.OrdinalIgnoreCase)); if (key == null) { quotedId = Adapter.QuoteIdentifier(type.Name + "ID"); key = columns.Where(c => c.ColumnName.Equals(quotedId, StringComparison.OrdinalIgnoreCase)).OrderByDescending(c => c.ColumnName.Contains(type.Name)).FirstOrDefault(); } if (key != null) { var requiredAttr = key.Property.GetCustomAttribute <System.ComponentModel.DataAnnotations.RequiredAttribute>(inherit); if (requiredAttr == null) { key.Attributes |= SqlColumnAttributes.AutoKey; } else { key.Attributes |= SqlColumnAttributes.Key; } keys.Add(key); } else { KeyColumns = Constants.SqlColumnsEmpty; } } if (keys.Count != 0) { KeyColumns = keys.ToArray(); if (KeyColumns.Count == 1 && KeyColumns[0].IsAutoKey && ExtraCrud.IsValidAutoIncrementType(KeyColumns[0].Type)) { AutoKeyColumn = KeyColumns[0]; } else if (autoKeyCount != 0 && KeyColumns.Count != autoKeyCount) { throw new InvalidOperationException(Type.FullName + " cannot have a both a composite key and an autoincrement key."); } else { // remove SqlColumnAttributes.AutoKey from all key columns SqlColumnAttributes invertedAutoKey = ~(SqlColumnAttributes.AutoKey ^ SqlColumnAttributes.Key); foreach (SqlColumn key in KeyColumns) { key.Attributes &= invertedAutoKey; } } } foreach (SqlColumn column in columns.Where(c => !c.IsKey)) { PropertyInfo prop = column.Property; bool selectOnly = !prop.CanRead || !prop.GetMethod.IsPublic || prop.GetMethod.IsStatic; if (selectOnly) { column.Attributes |= SqlColumnAttributes.IgnoreInsert | SqlColumnAttributes.IgnoreUpdate | SqlColumnAttributes.IgnoreDelete; } // Selects IgnoreSelectAttribute selectAttr = prop.GetCustomAttribute <IgnoreSelectAttribute>(inherit); if (selectAttr != null) { column.Attributes |= SqlColumnAttributes.IgnoreSelect; if (selectOnly) { continue; } } else if (selectOnly) { continue; } else { AutoSyncAttribute autoSyncAttr = prop.GetCustomAttribute <AutoSyncAttribute>(inherit); if (autoSyncAttr != null) { if (autoSyncAttr.SyncInsert) { column.Attributes |= SqlColumnAttributes.InsertAutoSync; } if (autoSyncAttr.SyncUpdate) { column.Attributes |= SqlColumnAttributes.UpdateAutoSync; } } if (InsertAutoSync) { column.Attributes |= SqlColumnAttributes.InsertAutoSync; } if (UpdateAutoSync) { column.Attributes |= SqlColumnAttributes.UpdateAutoSync; } } // Deletes MatchDeleteAttribute deleteAttr = prop.GetCustomAttribute <MatchDeleteAttribute>(inherit); if (deleteAttr != null || IgnoreDelete) { column.Attributes |= SqlColumnAttributes.IgnoreDelete; } readOnlyAttr = prop.GetCustomAttribute <ReadOnlyAttribute>(inherit); if (readOnlyAttr != null) { column.Attributes |= SqlColumnAttributes.IgnoreInsert | SqlColumnAttributes.IgnoreUpdate; continue; } var editableAttr = prop.GetCustomAttribute <System.ComponentModel.DataAnnotations.EditableAttribute>(inherit); if (editableAttr != null) { if (!editableAttr.AllowInitialValue) { column.Attributes |= SqlColumnAttributes.IgnoreUpdate; } if (!editableAttr.AllowEdit) { column.Attributes |= SqlColumnAttributes.IgnoreUpdate; } } // Inserts IgnoreInsertAttribute insertAttr = prop.GetCustomAttribute <IgnoreInsertAttribute>(inherit); if (insertAttr != null) { column.Attributes |= SqlColumnAttributes.IgnoreInsert; column.InsertValue = insertAttr.Value; if (insertAttr.AutoSync) { column.Attributes |= SqlColumnAttributes.InsertAutoSync; } } else if (IgnoreInsert) { column.Attributes |= SqlColumnAttributes.IgnoreInsert; } // Updates IgnoreUpdateAttribute ignoreUpdateAttr = prop.GetCustomAttribute <IgnoreUpdateAttribute>(inherit); if (ignoreUpdateAttr != null) { column.Attributes |= SqlColumnAttributes.IgnoreUpdate; column.UpdateValue = ignoreUpdateAttr.Value; if (ignoreUpdateAttr.AutoSync) { column.Attributes |= SqlColumnAttributes.UpdateAutoSync; } } else if (IgnoreUpdate) { column.Attributes = SqlColumnAttributes.IgnoreUpdate; } else { MatchUpdateAttribute matchUpdateAttr = prop.GetCustomAttribute <MatchUpdateAttribute>(inherit); //NOTE: MatchUpdate != IgnoreUpdate if (matchUpdateAttr != null) { column.Attributes |= SqlColumnAttributes.MatchUpdate; column.UpdateValue = matchUpdateAttr.Value; if (matchUpdateAttr.AutoSync) { column.Attributes |= SqlColumnAttributes.UpdateAutoSync; } } } } if (columns.Count == 0) { throw new InvalidOperationException(type.FullName + " does not have any valid properties."); // double check } Columns = columns.ToArray(); EqualityColumns = KeyColumns.Count == 0 || KeyColumns.Count == Columns.Count ? Columns : KeyColumns; UpdateKeyColumns = Columns == EqualityColumns ? Constants.SqlColumnsEmpty : Columns.Where(c => c.IsKey || c.MatchUpdate).ToArray(); DeleteKeyColumns = Columns == EqualityColumns ? Columns : Columns.Where(c => c.IsKey || c.MatchDelete).ToArray(); }
public static void TypeName_Set_ReturnsExpected(string value) { ColumnAttribute attribute = new ColumnAttribute() { TypeName = value }; Assert.Equal(value, attribute.TypeName); }
public void parse(object entity) { this._entity = entity; this._type = entity.GetType(); SetDBType(); //获得实体的属性集合 PropertyInfo[] props = _type.GetProperties(); this.ParameterNames = new List <String>(props.Length); this.ParameterValues = new List <Object>(props.Length); this.OutputNames = new List <String>(props.Length); this.OutputValues = new List <Object>(props.Length); this.KeyNames = new List <String>(1); this.KeyValues = new List <Object>(1); this.IsSqlServerIdentityTable = false; foreach (PropertyInfo prop in props) { string colName = prop.Name; object colValue = prop.GetValue(entity, null); bool isPK = false; //if is keyattribute return key object[] columnAttrs = prop.GetCustomAttributes(typeof(ColumnAttribute), true); ColumnAttribute colAttr = null; if (columnAttrs.Length > 0) { colAttr = columnAttrs[0] as ColumnAttribute; if (colAttr.Name != null) { colName = colAttr.Name; } isPK = colAttr.IsPrimaryKey; if (Object2SQL.TODO_INSERT == Todo) { if (ADOTemplate.DB_TYPE_SQLSERVER == this.dbType && colAttr.IsDbGenerated && !IsSqlServerIdentityTable) { IsSqlServerIdentityTable = true; OutputNames.Add(colName); } // 如果是oracle时,如果有seq定义,则取seq else if (ADOTemplate.DB_TYPE_ORACLE == this.dbType && colAttr.Expression != null && (colValue == null || colValue == (object)0)) { String seqSql = String.Format("select {0}.nextval from dual", colAttr.Expression); colValue = adoTemplate.GetLong(seqSql); OutputNames.Add(colName); OutputValues.Add(colValue); // 设置获取的Seq值到属性中 // prop.SetValue(entity, colValue, null); } } if (isPK) { this.KeyNames.Add(colName); this.KeyValues.Add(colValue); } else { if (colValue != null || Object2SQL.TODO_UPDATE == Todo) { this.ParameterNames.Add(colName); this.ParameterValues.Add(colValue); } } } } }
public SqlColumnBuilder(ColumnAttribute attribute) { Column = attribute; }
/// <summary> /// 访问 ToString 方法 /// </summary> /// <param name="node">即将访问的表达式</param> protected override Expression VisitToStringImpl(Expression node) { // => a.ID.ToString() // 字符串不进行转换 if (node == null || node.Type == typeof(string)) { return(_visitor.Visit(node)); } // 其它类型转字符串 bool isDate = node.Type == typeof(TimeSpan) || node.Type == typeof(TimeSpan?) || node.Type == typeof(DateTime) || node.Type == typeof(DateTime?) || node.Type == typeof(DateTimeOffset) || node.Type == typeof(DateTimeOffset?); if (isDate) { _builder.Append("TO_CHAR("); _visitor.Visit(node); string format = string.Empty; ColumnAttribute c = _visitedMark.Current != null?TypeUtils.GetColumnAttribute(_visitedMark.Current.Member, _visitedMark.Current.ReflectedType) : null; if (c != null && NpgUtils.IsTime(c.DbType)) { format = "hh24:mi:ss.us"; } else if (c != null && NpgUtils.IsDate(c.DbType)) { format = "yyyy-mm-dd"; } else if (c != null && (NpgUtils.IsDateTime(c.DbType) || NpgUtils.IsDateTime2(c.DbType))) { format = "yyyy-mm-dd hh24:mi:ss.us"; } else if (c != null && NpgUtils.IsDateTimeOffset(c.DbType)) { format = "yyyy-mm-dd hh24:mi:ss.us TZH:TZM"; } // 没有显式指定数据类型,则根据表达式的类型来判断 if (string.IsNullOrEmpty(format)) { if (node.Type == typeof(TimeSpan) || node.Type == typeof(TimeSpan?)) { format = "hh24:mi:ss.us"; } else if (node.Type == typeof(DateTime) || node.Type == typeof(DateTime?)) { format = "yyyy-mm-dd hh24:mi:ss.us"; } else if (node.Type == typeof(DateTimeOffset) || node.Type == typeof(DateTimeOffset?)) { format = "yyyy-mm-dd hh24:mi:ss.us TZH:TZM"; } } if (!string.IsNullOrEmpty(format)) { _builder.Append(",'"); _builder.Append(format); _builder.Append("'"); } _builder.Append(')'); } else if (node.Type == typeof(byte[])) { _builder.Append("ENCODE("); _visitor.Visit(node); _builder.Append(",'hex')"); } else { _builder.Append("CAST("); _visitor.Visit(node); _builder.Append(" AS VARCHAR)"); } return(node); }
public static string Convert(ColumnAttribute attr) { Types type; if (System.Enum.TryParse(attr.Type, out type)) { switch (type) { case Types.Bool: return("bool"); case Types.Byte: return("byte"); case Types.Char: return("char"); case Types.DateTime: return("DateTime"); case Types.Double: return("double"); case Types.Float: return("float"); case Types.Int: return("int"); case Types.Long: return("long"); case Types.GID: return("long"); case Types.LID: return("long"); case Types.String: return("string"); case Types.Short: return("short"); case Types.UShort: return("ushort"); case Types.UInt: return("uint"); case Types.ULong: return("ulong"); default: return("unknown type"); } } else { List <string> enums = new List <string>(); foreach (ModelType modelType in attr.DataGrid.ModelRoot.Types) { if (!(modelType is ExternalType)) { continue; } ExternalType typeEnum = modelType as ExternalType; enums.Add(typeEnum.Name); } if (enums.Contains(attr.Type)) { return(attr.Type); } } return("unknown type"); }
private void IntiailizeColumnAttribute(ColumnAttribute column) { alias = column.Alias; columnName = column.Name.HasValue() ? column.Name : member.Name; isComputed = column is ComputedColumnAttribute; sqlType = SqlType.Get(memberType, column); var id = column as IdAttribute; isPrimaryKey = id != null; if (id != null) { isGenerated = isPrimaryKey && id.IsDbGenerated; sequenceName = id.SequenceName; } isUpdatable = !isPrimaryKey && !isComputed; var version = column as VersionAttribute; if (version != null) { switch (sqlType.DbType) { case DBType.Int16: case DBType.Int32: case DBType.Int64: isVersion = true; break; default: throw new MappingException(string.Format(Res.VersionMemberTypeInvalid, sqlType.DbType.ToString(), this.entity.entityType.Name + "." + member.Name)); } } }
private Globals.ResultType LoadDataMemberInformation(MemberInfo memberInfo, Type dataType, BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance) { try { // Get Custom Attributes this.m_Attributes = memberInfo.GetCustomAttributes(false) .Select(attribute => (Attribute)attribute).ToList(); // Get First Column Attribute ColumnAttribute columnAttribute = (ColumnAttribute)this.Attributes .Where(attribute => attribute.GetType() == typeof(ColumnAttribute)).FirstOrDefault(); // Validation if (columnAttribute == null) { return(Globals.ResultType.Failure); } // Member Full Name this.m_FullName = memberInfo.Name; // Column Name this.m_ColumnName = columnAttribute.Name; // DataType this.m_DataType = dataType; // Sql DataType this.m_SqlDataType = DatabaseInformation.GetSqlTypeFromString(columnAttribute.DbType); // Nullable this.m_Nullable = columnAttribute.CanBeNull; // Is Primary Key this.m_IsPrimaryKey = columnAttribute.IsPrimaryKey; // Get First String Length Attribute StringLengthAttribute stringLengthAttribute = (StringLengthAttribute)this.Attributes .Where(attribute => attribute.GetType() == typeof(StringLengthAttribute)).FirstOrDefault(); // Validation if (stringLengthAttribute == null) { return(Globals.ResultType.Success); } // Max Length this.m_FieldLength = stringLengthAttribute.MaximumLength; // Max Length Error Message this.m_FieldLengthErrorMessage = stringLengthAttribute.ErrorMessage; return(Globals.ResultType.Success); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(Globals.ResultType.Failure); } }
public static void TypeName_Set_NullOrWhitespaceValue_ThrowsArgumentException(string value) { ColumnAttribute attribute = new ColumnAttribute(); Assert.Throws<ArgumentException>(null, () => attribute.TypeName = value); }
public void Initialize() { if (isInitialized) { return; } lock (this.initializeLock) { Dictionary <string, FieldInfo> rowFields; Dictionary <string, PropertyInfo> rowProperties; GetRowFieldsAndProperties(out rowFields, out rowProperties); foreach (var fieldInfo in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (fieldInfo.FieldType.IsSubclassOf(typeof(Field))) { var field = (Field)fieldInfo.GetValue(this); PropertyInfo property; if (!rowProperties.TryGetValue(fieldInfo.Name, out property)) { property = null; } ColumnAttribute column = null; DisplayNameAttribute display = null; SizeAttribute size = null; ExpressionAttribute expression = null; ScaleAttribute scale = null; MinSelectLevelAttribute selectLevel = null; ForeignKeyAttribute foreignKey = null; LeftJoinAttribute leftJoin = null; InnerJoinAttribute innerJoin = null; DefaultValueAttribute defaultValue = null; TextualFieldAttribute textualField = null; DateTimeKindAttribute dateTimeKind = null; FieldFlags addFlags = (FieldFlags)0; FieldFlags removeFlags = (FieldFlags)0; if (property != null) { column = property.GetCustomAttribute <ColumnAttribute>(false); display = property.GetCustomAttribute <DisplayNameAttribute>(false); size = property.GetCustomAttribute <SizeAttribute>(false); expression = property.GetCustomAttribute <ExpressionAttribute>(false); scale = property.GetCustomAttribute <ScaleAttribute>(false); selectLevel = property.GetCustomAttribute <MinSelectLevelAttribute>(false); foreignKey = property.GetCustomAttribute <ForeignKeyAttribute>(false); leftJoin = property.GetCustomAttributes <LeftJoinAttribute>(false).FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null); innerJoin = property.GetCustomAttributes <InnerJoinAttribute>(false).FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null); defaultValue = property.GetCustomAttribute <DefaultValueAttribute>(false); textualField = property.GetCustomAttribute <TextualFieldAttribute>(false); dateTimeKind = property.GetCustomAttribute <DateTimeKindAttribute>(false); var insertable = property.GetCustomAttribute <InsertableAttribute>(false); var updatable = property.GetCustomAttribute <UpdatableAttribute>(false); if (insertable != null && !insertable.Value) { removeFlags |= FieldFlags.Insertable; } if (updatable != null && !updatable.Value) { removeFlags |= FieldFlags.Updatable; } foreach (var attr in property.GetCustomAttributes <SetFieldFlagsAttribute>(false)) { addFlags |= attr.Add; removeFlags |= attr.Remove; } } if (ReferenceEquals(null, field)) { if (property == null) { throw new InvalidProgramException(String.Format( "Field {0} in type {1} is null and has no corresponding property in entity!", fieldInfo.Name, rowType.Name)); } object[] prm = new object[7]; prm[0] = this; // owner prm[1] = column == null ? property.Name : (column.Name.TrimToNull() ?? property.Name); prm[2] = display != null ? new LocalText(display.DisplayName) : null; prm[3] = size != null ? size.Value : 0; prm[4] = (FieldFlags.Default ^ removeFlags) | addFlags; prm[5] = null; prm[6] = null; FieldInfo storage; if (rowFields.TryGetValue("_" + property.Name, out storage) || rowFields.TryGetValue("m_" + property.Name, out storage) || rowFields.TryGetValue(property.Name, out storage)) { prm[5] = CreateFieldGetMethod(storage); prm[6] = CreateFieldSetMethod(storage); } field = (Field)Activator.CreateInstance(fieldInfo.FieldType, prm); fieldInfo.SetValue(this, field); } else { if (size != null) { throw new InvalidProgramException(String.Format( "Field size '{0}' in type {1} can't be overridden by Size attribute!", fieldInfo.Name, rowType.Name)); } if (display != null) { field.Caption = new LocalText(display.DisplayName); } if ((int)addFlags != 0 || (int)removeFlags != 0) { field.Flags = (field.Flags ^ removeFlags) | addFlags; } if (column != null && String.Compare(column.Name, field.Name, StringComparison.OrdinalIgnoreCase) != 0) { throw new InvalidProgramException(String.Format( "Field name '{0}' in type {1} can't be overridden by Column name attribute!", fieldInfo.Name, rowType.Name)); } } if (scale != null) { field.Scale = scale.Value; } if (defaultValue != null) { field.DefaultValue = defaultValue.Value; } if (selectLevel != null) { field.MinSelectLevel = selectLevel.Value; } if (expression != null) { field.Expression = expression.Value; } if (foreignKey != null) { field.ForeignTable = foreignKey.Table; field.ForeignField = foreignKey.Field; } if (leftJoin != null) { field.ForeignJoinAlias = new LeftJoin(this.joins, field.ForeignTable, leftJoin.Alias, new Criteria(leftJoin.Alias, field.ForeignField) == new Criteria(field)); } if (innerJoin != null) { field.ForeignJoinAlias = new InnerJoin(this.joins, field.ForeignTable, innerJoin.Alias, new Criteria(innerJoin.Alias, field.ForeignField) == new Criteria(field)); } if (textualField != null) { field.textualField = textualField.Value; } if (dateTimeKind != null && field is DateTimeField) { ((DateTimeField)field).DateTimeKind = dateTimeKind.Value; } if (property != null) { if (property.PropertyType != null && field is IEnumTypeField) { if (property.PropertyType.IsEnum) { (field as IEnumTypeField).EnumType = property.PropertyType; } else { var nullableType = Nullable.GetUnderlyingType(property.PropertyType); if (nullableType != null && nullableType.IsEnum) { (field as IEnumTypeField).EnumType = nullableType; } } } foreach (var attr in property.GetCustomAttributes <LeftJoinAttribute>()) { if (attr.ToTable != null && attr.OnCriteria != null) { new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field)); } } foreach (var attr in property.GetCustomAttributes <InnerJoinAttribute>()) { if (attr.ToTable != null && attr.OnCriteria != null) { new InnerJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field)); } } field.PropertyName = property.Name; this.byPropertyName[field.PropertyName] = field; field.CustomAttributes = property.GetCustomAttributes(false); } } } foreach (var attr in this.rowType.GetCustomAttributes <LeftJoinAttribute>()) { new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria)); } foreach (var attr in this.rowType.GetCustomAttributes <InnerJoinAttribute>()) { new InnerJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria)); } foreach (var attr in this.rowType.GetCustomAttributes <OuterApplyAttribute>()) { new OuterApply(this.joins, attr.InnerQuery, attr.Alias); } var propertyDescriptorArray = new PropertyDescriptor[this.Count]; for (int i = 0; i < this.Count; i++) { var field = this[i]; propertyDescriptorArray[i] = new FieldDescriptor(field); } this.propertyDescriptors = new PropertyDescriptorCollection(propertyDescriptorArray); InferTextualFields(); AfterInitialize(); } isInitialized = true; }
private Type DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false, List <ChoJSONRecordFieldConfiguration> recordFieldConfigurations = null, bool isTop = false) { if (recordType == null) { return(recordType); } if (!recordType.IsDynamicType()) { Type pt = null; if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any()) { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { pt = pd.PropertyType.GetUnderlyingType(); bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any(); if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1, recordFieldConfigurations, false); } else if (pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()) { var obj = new ChoJSONRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray()); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); if (recordFieldConfigurations != null) { if (!recordFieldConfigurations.Any(c => c.Name == pd.Name)) { recordFieldConfigurations.Add(obj); } } } } } else { if (isTop) { if (typeof(IList).IsAssignableFrom(recordType) || (recordType.IsGenericType && recordType.GetGenericTypeDefinition() == typeof(IList <>))) { throw new ChoParserException("Record type not supported."); } else if (typeof(IDictionary <string, object>).IsAssignableFrom(recordType)) { recordType = typeof(ExpandoObject); return(recordType); } else if (typeof(IDictionary).IsAssignableFrom(recordType)) { recordType = typeof(ExpandoObject); return(recordType); } } if (recordType.IsSimple()) { var obj = new ChoJSONRecordFieldConfiguration("Value", "$.Value"); obj.FieldType = recordType; recordFieldConfigurations.Add(obj); return(recordType); } foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { JsonIgnoreAttribute jiAttr = pd.Attributes.OfType <JsonIgnoreAttribute>().FirstOrDefault(); if (jiAttr != null) { continue; } pt = pd.PropertyType.GetUnderlyingType(); if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn, recordFieldConfigurations, false); } else { var obj = new ChoJSONRecordFieldConfiguration(pd.Name, ChoTypeDescriptor.GetPropetyAttribute <ChoJSONRecordFieldAttribute>(pd), pd.Attributes.OfType <Attribute>().ToArray()); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault(); if (slAttr != null && slAttr.MaximumLength > 0) { obj.Size = slAttr.MaximumLength; } ChoUseJSONSerializationAttribute sAttr = pd.Attributes.OfType <ChoUseJSONSerializationAttribute>().FirstOrDefault(); if (sAttr != null) { obj.UseJSONSerialization = sAttr.Flag; } ChoJSONPathAttribute jpAttr = pd.Attributes.OfType <ChoJSONPathAttribute>().FirstOrDefault(); if (jpAttr != null) { obj.JSONPath = jpAttr.JSONPath; } JsonPropertyAttribute jAttr = pd.Attributes.OfType <JsonPropertyAttribute>().FirstOrDefault(); if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace()) { obj.FieldName = jAttr.PropertyName; obj.JSONPath = jAttr.PropertyName; obj.Order = jAttr.Order; } else { DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault(); if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace()) { obj.FieldName = dnAttr.DisplayName.Trim(); } else { DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (dpAttr != null) { if (!dpAttr.ShortName.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.ShortName; } else if (!dpAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.Name; } obj.Order = dpAttr.Order; } else { ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault(); if (clAttr != null) { obj.Order = clAttr.Order; if (!clAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = clAttr.Name; } } } } } DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault(); if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace()) { obj.FormatText = dfAttr.DataFormatString; } if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace()) { obj.NullValue = dfAttr.NullDisplayText; } if (recordFieldConfigurations != null) { if (!recordFieldConfigurations.Any(c => c.Name == pd.Name)) { recordFieldConfigurations.Add(obj); } } } } } } return(recordType); }
/// <summary> /// Δημιουργεί ένα νέο αντικείμενο μεταδεδομένων στήλης / πεδίου οντότητας /// </summary> /// <param name="FieldInfo"></param> public ColumnMetadata(FieldInfo FieldInfo) { this.FieldInfo = FieldInfo ?? throw new ArgumentNullException(nameof(FieldInfo)); this.FieldInfo = FieldInfo; this.FieldName = FieldInfo.Name; this.FieldType = FieldInfo.FieldType; //Get Attributes ColumnAttribute column = this.FieldInfo.GetCustomAttribute <ColumnAttribute>(); CustomColumnAttribute customColumn = this.FieldInfo.GetCustomAttribute <CustomColumnAttribute>(); ManyToOneAttribute manyToOne = this.FieldInfo.GetCustomAttribute <ManyToOneAttribute>(); OneToManyAttribute oneToMany = this.FieldInfo.GetCustomAttribute <OneToManyAttribute>(); if (column == null && customColumn == null && oneToMany == null) { throw new MetadataException("This field does not contain any Column information"); } this.IsIdentifier = (this.FieldInfo.GetCustomAttribute <IdentityAttribute>() != null); if (column != null) { this.ColumnName = column.ColumnName; this.ColumnType = GetType(column.ColumnType); this.IsNullable = column.Nullable; this.IsUnique = column.Unique; } if (customColumn != null) { this.IsCustomColumn = true; //This is hardcoded since our database names the column that stores the value "CustomFieldValue" this.ColumnName = "CustomFieldValue"; this.ColumnType = GetType(customColumn.ColumnType); //Default values this.IsNullable = true; this.IsUnique = false; this.CustomFieldTable = customColumn.CustomTableName; this.CustomFieldId = customColumn.CustomFieldId; this.CustomFieldReference = customColumn.IdentifierColumn; } if (manyToOne != null) { this.IsRelationship = true; this.TargetEntity = manyToOne.TargetEntity; this.RelationshipReferenceColumn = manyToOne.IdentifierColumn; this.RelationshipType = RelationshipType.ManyToOne; } if (oneToMany != null) { this.IsRelationship = true; this.TargetEntity = oneToMany.TargetEntity; this.RelationshipReferenceColumn = oneToMany.IdentifierColumn; this.RelationshipType = RelationshipType.OneToMany; } //ADDED Row Guid this.IsRowGuid = (this.FieldInfo.GetCustomAttribute <GuidAttribute>() != null); var version = this.FieldInfo.GetCustomAttribute <VersionAttribute>(); IsVersion = (version != null); }
public override string CreateColumnQuery(PropertyInfo property, ColumnAttribute column) { var type = column.Type ?? property.PropertyType; var name = property.Name; var result = new StringBuilder(string.Format(" {0} ", name)); // Тип данных if (type == typeof(XmlDocument)) { result.Append("xml"); } else if (type == typeof(object)) { result.Append("sql_variant"); } else if (type == typeof(Guid)) { result.Append("uniqueidentifier"); } else if (type == typeof(DateTime)) { result.Append("datetime2"); } else if (type == typeof(DateTime?)) { result.Append("datetime2"); } else if (type == typeof(int)) { result.Append("int"); } else if (type == typeof(int?)) { result.Append("int"); } else if (type == typeof(long)) { result.Append("bigint"); } else if (type == typeof(long?)) { result.Append("bigint"); } else if (type == typeof(float)) { result.Append("float"); } else if (type == typeof(float?)) { result.Append("float"); } else if (type == typeof(decimal)) { result.Append("real"); } else if (type == typeof(decimal?)) { result.Append("real"); } else if (type == typeof(string)) { result.AppendFormat("nvarchar({0})", column.Size); } else if (type == typeof(bool)) { result.Append("bit"); } else if (type == typeof(bool?)) { result.Append("bit"); } else if (type.IsEnum) { result.Append("int"); } else { throw new Exception("Неизвестный тип данных"); } // Ограничения if (column.Primary) { result.Append(" PRIMARY KEY"); } if (column.AutoIncrement) { result.Append(" IDENTITY"); } if (column.Unique) { result.Append(" UNIQUE"); } if (column.NotNull) { result.Append(" NOT NULL"); } if (!string.IsNullOrEmpty(column.Default)) { result.AppendFormat(" DEFAULT {0}", column.Default); } // Результат return(result.ToString()); }
public static ILogins Parse(DataRow row, Type type) { object res = Activator.CreateInstance(type); if (type.IsClass) { PropertyInfo[] pis = type.GetProperties(); foreach (PropertyInfo pi in pis) { ColumnAttribute attr = pi.GetCustomAttribute <ColumnAttribute>(); if (attr == null) { continue; } string columnName = attr.Name; if (!row.Table.Columns.Contains(columnName)) { Console.WriteLine(string.Format("Parse: missed column name {0}", columnName)); continue; } object value = row[columnName]; if (value is DBNull) { pi.SetValue(res, null); } else { pi.SetValue(res, value); } } } else { TypedReference reference = __makeref(res); FieldInfo[] fis = type.GetFields(); foreach (FieldInfo fi in fis) { ColumnAttribute attr = fi.GetCustomAttribute <ColumnAttribute>(); if (attr == null) { continue; } string columnName = attr.Name; if (!row.Table.Columns.Contains(columnName)) { Console.WriteLine(string.Format("Parse: missed column name {0}", columnName)); continue; } object value = row[columnName]; if (value is DBNull) { fi.SetValueDirect(reference, null); } else { fi.SetValueDirect(reference, value); } } } return(res as ILogins); }
public TypeSchema(Type type) { this.type = type; propertySchemas = new Hashtable(); parentSchemas = new Hashtable(); childSchemas = new Hashtable(); Trace.WriteLineIf(DebugOutput.Enabled, "Creating TypeSchema for " + type.FullName); if (!type.IsSubclassOf(typeof(ServerObject))) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0} is not a subclass of ServerObject.", type.FullName)); } if (type.GetCustomAttributes(typeof(TableAttribute), false).Length != 1) { throw new ObjectServerException("Could not locate TableAttribute on type " + type.FullName); } if (!type.IsAbstract) { throw new ObjectServerException(type.FullName + " is not an abstract class"); } tableData = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false)[0]; Debug.Indent(); Trace.WriteLineIf(DebugOutput.Enabled, "TableName = " + tableData.TableName); Trace.WriteLineIf(DebugOutput.Enabled, "PrimaryKey = " + tableData.PrimaryKey); Trace.WriteLineIf(DebugOutput.Enabled, "PrimaryKeyType = " + tableData.KeyType); Trace.WriteLineIf(DebugOutput.Enabled, "DefaultOrder = " + tableData.DefaultOrder); Debug.Unindent(); PropertyInfo keyProperty = type.GetProperty(tableData.PrimaryKey, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (keyProperty == null) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "Could not locate the property {0} which is defined as the property for {1}", tableData.PrimaryKey, type.FullName)); } if (tableData.KeyType == PrimaryKeyType.Identity && keyProperty.PropertyType != typeof(int)) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "KeyType equals PrimaryKeyType.Identity and the property {0}.{1} is not System.Int32", type.FullName, keyProperty.Name)); } if (tableData.KeyType == PrimaryKeyType.Guid && keyProperty.PropertyType != typeof(Guid)) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "KeyType equals PrimaryKeyType.Guid and the property {0}.{1} is not System.Guid", type.FullName, keyProperty.Name)); } foreach (PropertyInfo propInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { Trace.WriteLineIf(DebugOutput.Enabled, "Checking property " + propInfo.Name); if (propInfo.GetCustomAttributes(typeof(ColumnAttribute), false).Length == 1) { if (propInfo.GetIndexParameters().Length != 0) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "Index properties ({0}.{1}) cannot be attributed with ColumnAttribute", type.FullName, propInfo.Name)); } if (!propInfo.CanRead) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must have an accessor", type.FullName, propInfo.Name)); } if (!propInfo.GetGetMethod(true).IsAbstract) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must be abstract", type.FullName, propInfo.Name)); } ColumnAttribute columnData = (ColumnAttribute)propInfo.GetCustomAttributes(typeof(ColumnAttribute), false)[0]; Debug.Indent(); Trace.WriteLineIf(DebugOutput.Enabled, "ColumnName = " + columnData.ColumnName);; Trace.WriteLineIf(DebugOutput.Enabled, "NullValue = " + columnData.NullValue); Debug.Unindent(); if (propInfo.Name == tableData.PrimaryKey && columnData.NullValue != null) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} is marked as the Primary Key and cannot have a NullValue", type.FullName, propInfo.Name)); } propertySchemas.Add(propInfo.Name, new PropertySchema(this, propInfo, columnData)); } else if (propInfo.GetCustomAttributes(typeof(ParentAttribute), false).Length == 1) { if (propInfo.GetIndexParameters().Length != 0) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "Index properties ({0}.{1}) cannot be attributed with ParentAttribute", type.FullName, propInfo.Name)); } if (!propInfo.CanRead) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must have an accessor", type.FullName, propInfo.Name)); } if (!propInfo.GetGetMethod(true).IsAbstract) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must be abstract", type.FullName, propInfo.Name)); } ParentAttribute parentData = (ParentAttribute)propInfo.GetCustomAttributes(typeof(ParentAttribute), false)[0]; if (parentData.DeleteAction == DeleteAction.Null && !parentData.CanBeNull) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} has DeleteAction.Null and CanBeNull is false", type.FullName, propInfo.Name)); } Debug.Indent(); Trace.WriteLineIf(DebugOutput.Enabled, "ColumnName = " + parentData.ColumnName); Trace.WriteLineIf(DebugOutput.Enabled, "ActionOnDelete = " + parentData.DeleteAction); Debug.Unindent(); parentSchemas.Add(propInfo.Name, new ParentSchema(this, propInfo, parentData)); } else if (propInfo.GetCustomAttributes(typeof(ChildrenAttribute), false).Length == 1) { if (propInfo.GetIndexParameters().Length != 0) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "Index properties ({0}.{1}) cannot be attributed with ChildrenAttribute", type.FullName, propInfo.Name)); } if (!propInfo.CanRead) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must have an accessor", type.FullName, propInfo.Name)); } if (propInfo.CanWrite) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must be read only", type.FullName, propInfo.Name)); } if (!propInfo.GetGetMethod(true).IsAbstract) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must be abstract", type.FullName, propInfo.Name)); } if (propInfo.PropertyType != typeof(ServerObjectCollection)) { throw new ObjectServerException(String.Format(CultureInfo.CurrentCulture, "{0}.{1} must be of type ServerObjectCollection", type.FullName, propInfo.Name)); } ChildrenAttribute childData = (ChildrenAttribute)propInfo.GetCustomAttributes(typeof(ChildrenAttribute), false)[0]; Debug.Indent(); Trace.WriteLineIf(DebugOutput.Enabled, "ChildType = " + childData.ChildType.FullName); Trace.WriteLineIf(DebugOutput.Enabled, "PropertyName = " + childData.PropertyName); Debug.Unindent(); childSchemas.Add(propInfo.Name, new ChildrenSchema(this, propInfo, childData)); } } proxyType = ProxyBuilder.BuildProxy(type); }
private static void AppendColumnEqParameter(StringBuilder sqlBuilder, DbProvider dbProvider, ColumnAttribute column) { sqlBuilder.AppendFormat("{0}{1}{2}={3}{4}", dbProvider.ParameterNamePrefix, column.Name, dbProvider.ParameterNameSuffix, dbProvider.ParameterPrefix, column.Property.Name); }
public ColumnAttribute GetEntityColumnAttribute(Type type, PropertyInfo proto) { ColumnAttribute attr = null; if (_orm.Aop.ConfigEntityPropertyHandler != null) { var aope = new Aop.ConfigEntityPropertyEventArgs(type, proto); _orm.Aop.ConfigEntityPropertyHandler(_orm, aope); attr = aope.ModifyResult; } if (attr == null) { attr = new ColumnAttribute(); } if (dicConfigEntity.TryGetValue(type, out var trytb) && trytb._columns.TryGetValue(proto.Name, out var trycol)) { if (!string.IsNullOrEmpty(trycol.Name)) { attr.Name = trycol.Name; } if (!string.IsNullOrEmpty(trycol.OldName)) { attr.OldName = trycol.OldName; } if (!string.IsNullOrEmpty(trycol.DbType)) { attr.DbType = trycol.DbType; } if (trycol._IsPrimary != null) { attr._IsPrimary = trycol.IsPrimary; } if (trycol._IsIdentity != null) { attr._IsIdentity = trycol.IsIdentity; } if (trycol._IsNullable != null) { attr._IsNullable = trycol.IsNullable; } if (trycol._IsIgnore != null) { attr._IsIgnore = trycol.IsIgnore; } if (trycol._IsVersion != null) { attr._IsVersion = trycol.IsVersion; } if (trycol.MapType != null) { attr.MapType = trycol.MapType; } if (trycol._Position != null) { attr._Position = trycol.Position; } if (trycol._CanInsert != null) { attr._CanInsert = trycol.CanInsert; } if (trycol._CanUpdate != null) { attr._CanUpdate = trycol.CanUpdate; } if (trycol.ServerTime != DateTimeKind.Unspecified) { attr.ServerTime = trycol.ServerTime; } if (trycol._StringLength != null) { attr.StringLength = trycol.StringLength; } if (!string.IsNullOrEmpty(trycol.InsertValueSql)) { attr.InsertValueSql = trycol.InsertValueSql; } if (trycol._Precision != null) { attr.Precision = trycol.Precision; } if (trycol._Scale != null) { attr.Scale = trycol.Scale; } } var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); foreach (var tryattrobj in attrs) { var tryattr = tryattrobj as ColumnAttribute; if (tryattr == null) { continue; } if (!string.IsNullOrEmpty(tryattr.Name)) { attr.Name = tryattr.Name; } if (!string.IsNullOrEmpty(tryattr.OldName)) { attr.OldName = tryattr.OldName; } if (!string.IsNullOrEmpty(tryattr.DbType)) { attr.DbType = tryattr.DbType; } if (tryattr._IsPrimary != null) { attr._IsPrimary = tryattr.IsPrimary; } if (tryattr._IsIdentity != null) { attr._IsIdentity = tryattr.IsIdentity; } if (tryattr._IsNullable != null) { attr._IsNullable = tryattr.IsNullable; } if (tryattr._IsIgnore != null) { attr._IsIgnore = tryattr.IsIgnore; } if (tryattr._IsVersion != null) { attr._IsVersion = tryattr.IsVersion; } if (tryattr.MapType != null) { attr.MapType = tryattr.MapType; } if (tryattr._Position != null) { attr._Position = tryattr.Position; } if (tryattr._CanInsert != null) { attr._CanInsert = tryattr.CanInsert; } if (tryattr._CanUpdate != null) { attr._CanUpdate = tryattr.CanUpdate; } if (tryattr.ServerTime != DateTimeKind.Unspecified) { attr.ServerTime = tryattr.ServerTime; } if (tryattr._StringLength != null) { attr.StringLength = tryattr.StringLength; } if (!string.IsNullOrEmpty(tryattr.InsertValueSql)) { attr.InsertValueSql = tryattr.InsertValueSql; } if (tryattr._Precision != null) { attr.Precision = tryattr.Precision; } if (tryattr._Scale != null) { attr.Scale = tryattr.Scale; } } ColumnAttribute ret = null; if (!string.IsNullOrEmpty(attr.Name)) { ret = attr; } if (!string.IsNullOrEmpty(attr.OldName)) { ret = attr; } if (!string.IsNullOrEmpty(attr.DbType)) { ret = attr; } if (attr._IsPrimary != null) { ret = attr; } if (attr._IsIdentity != null) { ret = attr; } if (attr._IsNullable != null) { ret = attr; } if (attr._IsIgnore != null) { ret = attr; } if (attr._IsVersion != null) { ret = attr; } if (attr.MapType != null) { ret = attr; } if (attr._Position != null) { ret = attr; } if (attr._CanInsert != null) { ret = attr; } if (attr._CanUpdate != null) { ret = attr; } if (attr.ServerTime != DateTimeKind.Unspecified) { ret = attr; } if (attr._StringLength != null) { ret = attr; } if (!string.IsNullOrEmpty(attr.InsertValueSql)) { ret = attr; } if (attr._Precision != null) { ret = attr; } if (attr._Scale != null) { ret = attr; } if (ret != null && ret.MapType == null) { ret.MapType = proto.PropertyType; } return(ret); }
// 创建 INSRT 命令 protected override Command ResolveInsertCommand <T>(DbQueryableInfo_Insert <T> dbQuery, ResolveToken token) { ISqlBuilder builder = this.CreateSqlBuilder(token); TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo <T>(); TableAliasCache aliases = new TableAliasCache(); if (dbQuery.Entity != null) { // 如果没有Sequence列,使用 INSERT ALL INTO 语法,否则就一条一条逐行写入~~ // 批量 INSERT,自增列不会自动赋值 object entity = dbQuery.Entity; ISqlBuilder columnsBuilder = this.CreateSqlBuilder(token); ISqlBuilder valuesBuilder = this.CreateSqlBuilder(token); // 指定插入列 MemberInvokerCollection invokers = typeRuntime.Invokers; if (dbQuery.EntityColumns != null && dbQuery.EntityColumns.Count > 0) { invokers = new MemberInvokerCollection(); for (int i = 0; i < dbQuery.EntityColumns.Count; i++) { Expression curExpr = dbQuery.EntityColumns[i]; if (curExpr.NodeType == ExpressionType.Lambda) { curExpr = (curExpr as LambdaExpression).Body.ReduceUnary(); } if (curExpr.NodeType != ExpressionType.MemberAccess) { throw new XFrameworkException("Can't read field name from expression {0}", dbQuery.EntityColumns[i]); } MemberExpression member = curExpr as MemberExpression; string name = member.Member.Name; invokers[name] = typeRuntime.Invokers[name]; } } // 自增列参数 IDbDataParameter seqParameter = null; // 自增列标记 ColumnAttribute seqColumn = null; foreach (var invoker in invokers) { var column = invoker.Column; if (column != null && column.NoMapped) { continue; } if (invoker.ForeignKey != null) { continue; } if (invoker.Member.MemberType == System.Reflection.MemberTypes.Method) { continue; } columnsBuilder.AppendMember(invoker.Member.Name); columnsBuilder.Append(','); if (invoker == dbQuery.AutoIncrement) { seqColumn = column; if (dbQuery.Bulk == null) { // 非批量INSERT,产生一个 OUTPUT 类型的参数 string pName = string.Format("{0}p{1}", this.ParameterPrefix, token.Parameters.Count); var database = dbQuery.SourceQuery.DbContext.Database; seqParameter = database.CreateParameter(pName, -1, direction: ParameterDirection.Output); token.Parameters.Add(seqParameter); valuesBuilder.Append(seqParameter.ParameterName); valuesBuilder.Append(','); } else { valuesBuilder.Append(((OracleColumnAttribute)column).SEQName); valuesBuilder.Append(".NEXTVAL"); valuesBuilder.Append(','); } } else { var value = invoker.Invoke(entity); string seg = this.DbValue.GetSqlValueWidthDefault(value, token, column); valuesBuilder.Append(seg); valuesBuilder.Append(','); } } columnsBuilder.Length -= 1; valuesBuilder.Length -= 1; if (dbQuery.Bulk == null) { // 非批量INSERT,产生一个 OUTPUT 类型的参数 if (seqParameter != null) { seqParameter.Direction = ParameterDirection.Output; seqParameter.DbType = DbType.Int64; builder.Append("SELECT "); builder.Append(((OracleColumnAttribute)seqColumn).SEQName); builder.Append(".NEXTVAL INTO "); builder.Append(seqParameter.ParameterName); builder.Append(" FROM DUAL;"); builder.AppendNewLine(); //useSEQ = true; } builder.Append("INSERT "); } else { // 批量 INSERT if (!dbQuery.Bulk.OnlyValue || seqColumn != null) { builder.Append("INSERT "); } // 如果有自增列则不使用 INSERT ALL INTO 语法 if (!dbQuery.Bulk.OnlyValue && seqColumn == null) { builder.Append("ALL "); } } builder.Append("INTO "); builder.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary); builder.Append('('); builder.Append(columnsBuilder); builder.Append(')'); builder.AppendNewLine(); builder.AppendNewTab(); builder.Append("VALUES"); builder.Append('('); builder.Append(valuesBuilder); builder.Append(')'); if (dbQuery.Bulk == null) { builder.Append(';'); } else { if (seqColumn != null) { if (dbQuery.Bulk.IsEndPos) { builder.Append(";"); } else { builder.AppendNewLine(";"); } } else { builder.AppendNewLine(); if (dbQuery.Bulk.IsEndPos) { builder.Append("SELECT 1 FROM DUAL;"); } } } } else if (dbQuery.SelectInfo != null) { builder.Append("INSERT INTO "); builder.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary); builder.Append('('); int i = 0; MapperCommand cmd2 = this.ResolveSelectCommand(dbQuery.SelectInfo, 0, false, token) as MapperCommand; foreach (var column in cmd2.PickColumns) { builder.AppendMember(column.Name); if (i < cmd2.PickColumns.Count - 1) { builder.Append(','); } i++; } builder.Append(')'); builder.AppendNewLine(); builder.Append(cmd2.CommandText); builder.Append(';'); } var cmd = new Command(builder.ToString(), builder.Token != null ? builder.Token.Parameters : null, System.Data.CommandType.Text); return(cmd); }
internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) { if (entity.FullName.StartsWith("<>f__AnonymousType")) { return(null); } if (_cacheGetTableByEntity.TryGetValue($"{common.QuoteSqlName("db")}{entity.FullName}", out var trytb)) { return(trytb); //区分数据库类型缓存 } if (common.CodeFirst.GetDbInfo(entity) != null) { return(null); } var tbattr = entity.GetCustomAttributes(typeof(TableAttribute), false).LastOrDefault() as TableAttribute; trytb = new TableInfo(); trytb.Type = entity; trytb.Properties = entity.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); trytb.CsName = entity.Name; trytb.DbName = (tbattr?.Name ?? entity.Name); trytb.DbOldName = tbattr?.OldName; if (common.CodeFirst.IsSyncStructureToLower) { trytb.DbName = trytb.DbName.ToLower(); trytb.DbOldName = trytb.DbOldName?.ToLower(); } trytb.SelectFilter = tbattr?.SelectFilter; foreach (var p in trytb.Properties.Values) { var tp = common.CodeFirst.GetDbInfo(p.PropertyType); //if (tp == null) continue; var colattr = p.GetCustomAttributes(typeof(ColumnAttribute), false).LastOrDefault() as ColumnAttribute; if (tp == null && colattr == null) { continue; } if (colattr == null) { colattr = new ColumnAttribute { Name = p.Name, DbType = tp.Value.dbtypeFull, IsIdentity = false, IsNullable = tp.Value.isnullable ?? true, IsPrimary = false, } } ; if (string.IsNullOrEmpty(colattr.DbType)) { colattr.DbType = tp?.dbtypeFull ?? "varchar(255)"; } colattr.DbType = colattr.DbType.ToUpper(); if (tp != null && tp.Value.isnullable == null) { colattr.IsNullable = tp.Value.dbtypeFull.Contains("NOT NULL") == false; } if (colattr.DbType?.Contains("NOT NULL") == true) { colattr.IsNullable = false; } if (string.IsNullOrEmpty(colattr.Name)) { colattr.Name = p.Name; } if (common.CodeFirst.IsSyncStructureToLower) { colattr.Name = colattr.Name.ToLower(); } if ((colattr.IsNullable == false || colattr.IsIdentity || colattr.IsPrimary) && colattr.DbType.Contains("NOT NULL") == false) { colattr.DbType += " NOT NULL"; } if (colattr.IsNullable == true && colattr.DbType.Contains("NOT NULL")) { colattr.DbType = colattr.DbType.Replace("NOT NULL", ""); } colattr.DbType = Regex.Replace(colattr.DbType, @"\([^\)]+\)", m => Regex.Replace(m.Groups[0].Value, @"\s", "")); colattr.DbDefautValue = trytb.Properties[p.Name].GetValue(Activator.CreateInstance(trytb.Type)); if (colattr.DbDefautValue == null) { colattr.DbDefautValue = tp?.defaultValue; } if (colattr.IsNullable == false && colattr.DbDefautValue == null) { var consturctorType = p.PropertyType.GenericTypeArguments.FirstOrDefault() ?? p.PropertyType; colattr.DbDefautValue = Activator.CreateInstance(consturctorType); } var col = new ColumnInfo { Table = trytb, CsName = p.Name, CsType = p.PropertyType, Attribute = colattr }; trytb.Columns.Add(colattr.Name, col); trytb.ColumnsByCs.Add(p.Name, col); } trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary).ToArray(); if (trytb.Primarys.Any() == false) { trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity).ToArray(); } _cacheGetTableByEntity.TryAdd(entity.FullName, trytb); return(trytb); }
/// <summary> /// 动态函数 /// </summary> /// <param name="type"></param> /// <param name="attribute"></param> public ToArray(Type type, ColumnAttribute attribute) { this.attribute = attribute; dynamicMethod = new DynamicMethod("SqlColumnToArray", null, new Type[] { type, typeof(object[]), Field.RefIntType }, type, true); generator = dynamicMethod.GetILGenerator(); }
/// <summary> /// 访问 ToString 方法 /// </summary> protected override Expression VisitToStringImpl(Expression node) { // => a.ID.ToString() // 字符串不进行转换 if (node == null || node.Type == typeof(string)) { return(_visitor.Visit(node)); } ColumnAttribute column = null; bool isUnicode = _provider.DbValue.IsUnicode(_visitedMark.Current, out column); bool isBytes = node.Type == typeof(byte[]); bool isDate = node.Type == typeof(DateTime) || node.Type == typeof(DateTime?) || node.Type == typeof(TimeSpan) || node.Type == typeof(TimeSpan?) || node.Type == typeof(DateTimeOffset) || node.Type == typeof(DateTimeOffset?); if (!isBytes) { if (isUnicode) { _builder.Append("TO_NCHAR("); } else { _builder.Append("TO_CHAR("); } } // 其它类型转字符串 if (isDate) { _visitor.Visit(node); string format = string.Empty; ColumnAttribute c = _provider.DbValue.GetColumnAttribute(_visitedMark.Current); if (c != null && DbTypeUtils.IsDate(c.DbType)) { format = "yyyy-mm-dd"; } else if (c != null && (DbTypeUtils.IsDateTime(c.DbType) || DbTypeUtils.IsDateTime2(c.DbType))) { format = "yyyy-mm-dd hh24:mi:ss.ff"; } else if (c != null && DbTypeUtils.IsDateTimeOffset(c.DbType)) { format = "yyyy-mm-dd hh24:mi:ss.ff tzh:tzm"; } // 没有显式指定数据类型,则根据表达式的类型来判断 if (string.IsNullOrEmpty(format)) { if (node.Type == typeof(DateTime) || node.Type == typeof(DateTime?)) { format = "yyyy-mm-dd hh24:mi:ss.ff"; } else if (node.Type == typeof(DateTimeOffset) || node.Type == typeof(DateTimeOffset?)) { format = "yyyy-mm-dd hh24:mi:ss.ff tzh:tzm"; } } if (!string.IsNullOrEmpty(format)) { _builder.Append(",'"); _builder.Append(format); _builder.Append("'"); } } else if (isBytes) { _builder.Append("RTRIM(DBMS_LOB.SUBSTR("); _visitor.Visit(node); _builder.Append(')'); } else if (node.Type == typeof(Guid)) { _builder.Append("REGEXP_REPLACE(REGEXP_REPLACE("); _visitor.Visit(node); _builder.Append(@",'(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5'),'(.{2})(.{2})(.{2})(.{2}).(.{2})(.{2}).(.{2})(.{2})(.{18})','\4\3\2\1-\6\5-\8\7\9')"); } else { _visitor.Visit(node); } _builder.Append(')'); return(node); }
internal ColumnAttribute GetEntityColumnAttribute(Type type, PropertyInfo proto) { ColumnAttribute attr = null; if (_orm.Aop.ConfigEntityProperty != null) { var aope = new AopConfigEntityPropertyEventArgs(type, proto); _orm.Aop.ConfigEntityProperty(_orm, aope); attr = aope.ModifyResult; } if (attr == null) { attr = new ColumnAttribute(); } if (dicConfigEntity.TryGetValue(type, out var trytb) && trytb._columns.TryGetValue(proto.Name, out var trycol)) { if (!string.IsNullOrEmpty(trycol.Name)) { attr.Name = trycol.Name; } if (!string.IsNullOrEmpty(trycol.OldName)) { attr.OldName = trycol.OldName; } if (!string.IsNullOrEmpty(trycol.DbType)) { attr.DbType = trycol.DbType; } if (trycol._IsPrimary != null) { attr._IsPrimary = trycol.IsPrimary; } if (trycol._IsIdentity != null) { attr._IsIdentity = trycol.IsIdentity; } if (trycol._IsNullable != null) { attr._IsNullable = trycol.IsNullable; } if (trycol._IsIgnore != null) { attr._IsIgnore = trycol.IsIgnore; } if (trycol._IsVersion != null) { attr._IsVersion = trycol.IsVersion; } if (trycol.DbDefautValue != null) { attr.DbDefautValue = trycol.DbDefautValue; } } var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); foreach (var tryattrobj in attrs) { var tryattr = tryattrobj as ColumnAttribute; if (tryattr == null) { continue; } if (!string.IsNullOrEmpty(tryattr.Name)) { attr.Name = tryattr.Name; } if (!string.IsNullOrEmpty(tryattr.OldName)) { attr.OldName = tryattr.OldName; } if (!string.IsNullOrEmpty(tryattr.DbType)) { attr.DbType = tryattr.DbType; } if (tryattr._IsPrimary != null) { attr._IsPrimary = tryattr.IsPrimary; } if (tryattr._IsIdentity != null) { attr._IsIdentity = tryattr.IsIdentity; } if (tryattr._IsNullable != null) { attr._IsNullable = tryattr.IsNullable; } if (tryattr._IsIgnore != null) { attr._IsIgnore = tryattr.IsIgnore; } if (tryattr._IsVersion != null) { attr._IsVersion = tryattr.IsVersion; } if (tryattr.DbDefautValue != null) { attr.DbDefautValue = tryattr.DbDefautValue; } } if (!string.IsNullOrEmpty(attr.Name)) { return(attr); } if (!string.IsNullOrEmpty(attr.OldName)) { return(attr); } if (!string.IsNullOrEmpty(attr.DbType)) { return(attr); } if (attr._IsPrimary != null) { return(attr); } if (attr._IsIdentity != null) { return(attr); } if (attr._IsNullable != null) { return(attr); } if (attr._IsIgnore != null) { return(attr); } if (attr._IsVersion != null) { return(attr); } if (attr.DbDefautValue != null) { return(attr); } return(null); }
internal static void PopulateFromProperty(object objValue, PropertyInfo pi, ref ColumnInfo ci, out ColumnAttribute columnAttr) { //验证Table修饰符 var isExplicit = pi.DeclaringType.GetCustomAttributes(typeof(TableAttribute), true).Any(); var tableAttr = pi.DeclaringType.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault() as TableAttribute; columnAttr = pi.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() as ColumnAttribute; var isIgnore = pi.GetCustomAttributes(typeof(IgnoreAttribute), true).Any(); if (isIgnore || (isExplicit && columnAttr == null)) { ci = null; } else if (objValue == null) { ci = null; } else { ci = ci ?? new ColumnInfo(); ci.ColumnName = columnAttr.NameAs; ci.ColumnType = columnAttr.ColumnTypeAs ?? pi.PropertyType; ci.IsClass = RefletUtil.IsClass(pi.PropertyType); ci.IsGenric = RefletUtil.IsListGeneric(pi.PropertyType); ci.IsBaseType = RefletUtil.IsBaseType(pi.PropertyType); ci.IsTableAs = string.IsNullOrEmpty(columnAttr.TableNameAs); ci.TableNameAs = string.IsNullOrEmpty(columnAttr.TableNameAs) ? tableAttr.TableName : columnAttr.TableNameAs; ci.DBType = columnAttr.DbTypeAs == TargetDbType.Oracle ? "ORACLE" : "SQLSERVER"; object colValue = new BuildColumn() { PropertyInfo = pi }.GetValue(objValue); if (colValue != null) { if (!columnAttr.HasExtendies) { ci.Value = Convert.ChangeType(colValue, ci.ColumnType); } else { MethodInfo method = pi.DeclaringType.GetMethod(columnAttr.FormatFuncName); ExtensionsResult extensions = (ExtensionsResult)method.Invoke(objValue, new object[] { colValue }); ci.Value = extensions.Value; ci.ColumnType = extensions.ValueType; } ci.IsNull = false; } else { ci.IsNull = true; } } }
internal static SqlType Get(Type memberType, ColumnAttribute col) { SqlType result = null; DBType dbType = col.DbType; string key = null; if (col.DbType == DBType.Unkonw) { var typeKey = memberType.TypeHandle.Value.GetHashCode(); if (col.Length == 0 && col.IsNullable && col.Precision == 0 && col.Scale == 0) { if (defaultTypes.TryGetValue(typeKey, out result)) return result; } var underlyingType = memberType; if (underlyingType.IsNullable()) underlyingType = Nullable.GetUnderlyingType(underlyingType); if (underlyingType.IsEnum) underlyingType = Enum.GetUnderlyingType(underlyingType); //if (!TypeMap.TryGetValue(underlyingType.TypeHandle.Value.GetHashCode(), out dbType)) // throw new NotSupportedException("Not support '" + underlyingType.FullName + "' for field or property type."); typeKey = underlyingType.TypeHandle.Value.GetHashCode(); if (TypeMap.TryGetValue(typeKey, out dbType)) { key = string.Concat(typeKey, col.Length, col.IsNullable, col.Precision, col.Scale); if (SqlTypes.TryGetValue(key, out result)) return result; defaultTypes.TryGetValue(typeKey, out result); } } else { key = string.Concat(col.DbType, col.Length, col.IsNullable, col.Precision, col.Scale); if (SqlTypes.TryGetValue(key, out result)) return result; result = new SqlType(col.DbType); } if (result != null) dbType = result.DbType; result = new SqlType(dbType, col.Precision, col.Scale) { Length = col.Length, Required = !col.IsNullable }; lock (SqlTypes) SqlTypes.Add(key, result); return result; }
public static void TypeName_Set_NullOrWhitespaceValue_ThrowsArgumentException(string value) { ColumnAttribute attribute = new ColumnAttribute(); AssertExtensions.Throws <ArgumentException>("value", null, () => attribute.TypeName = value); }
/// <summary> Write a Column XML Element from attributes in a member. </summary> public virtual void WriteColumn(System.Xml.XmlWriter writer, System.Reflection.MemberInfo member, ColumnAttribute attribute, BaseAttribute parentAttribute, System.Type mappedClass) { writer.WriteStartElement( "column" ); // Attribute: <name> writer.WriteAttributeString("name", attribute.Name==null ? DefaultHelper.Get_Column_Name_DefaultValue(member) : GetAttributeValue(attribute.Name, mappedClass)); // Attribute: <length> if(attribute.Length != -1) writer.WriteAttributeString("length", attribute.Length.ToString()); // Attribute: <precision> if(attribute.Precision != -1) writer.WriteAttributeString("precision", attribute.Precision.ToString()); // Attribute: <scale> if(attribute.Scale != -1) writer.WriteAttributeString("scale", attribute.Scale.ToString()); // Attribute: <not-null> if( attribute.NotNullSpecified ) writer.WriteAttributeString("not-null", attribute.NotNull ? "true" : "false"); // Attribute: <unique> if( attribute.UniqueSpecified ) writer.WriteAttributeString("unique", attribute.Unique ? "true" : "false"); // Attribute: <unique-key> if(attribute.UniqueKey != null) writer.WriteAttributeString("unique-key", GetAttributeValue(attribute.UniqueKey, mappedClass)); // Attribute: <sql-type> if(attribute.SqlType != null) writer.WriteAttributeString("sql-type", GetAttributeValue(attribute.SqlType, mappedClass)); // Attribute: <index> if(attribute.Index != null) writer.WriteAttributeString("index", GetAttributeValue(attribute.Index, mappedClass)); // Attribute: <check> if(attribute.Check != null) writer.WriteAttributeString("check", GetAttributeValue(attribute.Check, mappedClass)); // Attribute: <default> if(attribute.Default != null) writer.WriteAttributeString("default", GetAttributeValue(attribute.Default, mappedClass)); WriteUserDefinedContent(writer, member, null, attribute); System.Collections.ArrayList memberAttribs = GetSortedAttributes(member); int attribPos; // Find the position of the ColumnAttribute (its <sub-element>s must be after it) for(attribPos=0; attribPos<memberAttribs.Count; attribPos++) if( memberAttribs[attribPos] is ColumnAttribute && ((BaseAttribute)memberAttribs[attribPos]).Position == attribute.Position ) break; // found int i = attribPos + 1; // Element: <comment> for(; i<memberAttribs.Count; i++) { BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute; if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType()) || IsNextElement(memberAttrib, attribute, typeof(CommentAttribute)) ) break; // next attributes are 'elements' of the same level OR for 'sub-elements' else { if( memberAttrib is ColumnAttribute ) break; // Following attributes are for this Column if( memberAttrib is CommentAttribute ) WriteComment(writer, member, memberAttrib as CommentAttribute, attribute, mappedClass); } } WriteUserDefinedContent(writer, member, typeof(CommentAttribute), attribute); writer.WriteEndElement(); }
private static string WrapColumnEqParameter(DbProvider dbProvider, ColumnAttribute col) { return ($"{dbProvider.ParameterNamePrefix}{col.Name}{dbProvider.ParameterNameSuffix}={dbProvider.ParameterPrefix}{col.Property.Name}"); }
public static void Order_Set_ReturnsExpected(int value) { ColumnAttribute attribute = new ColumnAttribute() { Order = value }; Assert.Equal(value, attribute.Order); }
public static IEnumerable <string> GetModeledDataProperties(Type t) { foreach (PropertyInfo prop in t.GetProperties()) { string tableName = t.ToString(); if (tableName.Contains('.')) { int lastIndex = tableName.LastIndexOf('.'); tableName = tableName.Substring(lastIndex + 1, tableName.Length - lastIndex - 1); } MemberInfo info = prop; ModeledDataAttribute attrib = null; ModeledDataTypeAttribute typeAttrib = null; ModeledDataNullableAttribute nullableAttrib = null; ColumnAttribute columnAttribute = null; foreach (object attribObject in info.GetCustomAttributes(true)) { if (attribObject is ModeledDataAttribute) { attrib = attribObject as ModeledDataAttribute; } else if (attribObject is ModeledDataTypeAttribute) { typeAttrib = attribObject as ModeledDataTypeAttribute; } else if (attribObject is ModeledDataNullableAttribute) { nullableAttrib = attribObject as ModeledDataNullableAttribute; } else if (attribObject is ColumnAttribute) { columnAttribute = attribObject as ColumnAttribute; } } // Check for nullable types bool isNullable = false; Type propType = prop.PropertyType; if (propType.Name.StartsWith("Nullable")) { propType = Nullable.GetUnderlyingType(propType); isNullable = true; } // Has a ColumnAttribute if (columnAttribute != null) { if (propType == typeof(String)) { isNullable = true; } if (isNullable && !columnAttribute.CanBeNull) { isNullable = false; } yield return(tableName + "." + (!string.IsNullOrEmpty(columnAttribute.Name) ? columnAttribute.Name : prop.Name) + " " + GetSqlTypeString(!string.IsNullOrEmpty(columnAttribute.DbType) ? columnAttribute.DbType : propType.Name, isNullable)); } // Has a ModeledDataAttribute else if (attrib != null) { if (attrib.Alias1Name == null) { yield return(tableName + "." + prop.Name + " " + GetSqlTypeString( (((typeAttrib != null) && (typeAttrib.Alias1Type != null)) ? typeAttrib.Alias1Type : propType.Name), ((nullableAttrib != null) || isNullable))); } else { yield return(tableName + "." + attrib.Alias1Name + " " + GetSqlTypeString( (((typeAttrib != null) && (typeAttrib.Alias1Type != null)) ? typeAttrib.Alias1Type : propType.Name), ((nullableAttrib != null) || isNullable))); } if (typeAttrib != null) { if (attrib.Alias2Name != null) { yield return(tableName + "." + attrib.Alias2Name + " " + GetSqlTypeString(typeAttrib.Alias2Type, (nullableAttrib != null))); } if (attrib.Alias3Name != null) { yield return(tableName + "." + attrib.Alias3Name + " " + GetSqlTypeString(typeAttrib.Alias3Type, (nullableAttrib != null))); } if (attrib.Alias4Name != null) { yield return(tableName + "." + attrib.Alias4Name + " " + GetSqlTypeString(typeAttrib.Alias4Type, (nullableAttrib != null))); } } } } }
public static void Order_Set_NegativeValue_ThrowsArgumentOutOfRangeException() { ColumnAttribute attribute = new ColumnAttribute(); Assert.Throws<ArgumentOutOfRangeException>("value", () => attribute.Order = -1); }
/// <summary> /// Inspect a member and optionally add a ColumnMap. /// </summary> /// <param name="entityType">The entity type that is being mapped.</param> /// <param name="member">The member that is being mapped.</param> /// <param name="columnMaps">The ColumnMapCollection that is being created.</param> protected abstract void CreateColumnMap(Type entityType, MemberInfo member, ColumnAttribute columnAtt, ColumnMapCollection columnMaps);
/// <summary> /// Generate Dictonary type based on models property /// </summary> /// <typeparam name="T"></typeparam> /// <param name="modeltoConvert"></param> /// <param name="properties"></param> /// <returns></returns> private static IDictionary <string, object> GenerateDBEntityFromProperty <T>(T modeltoConvert, IList <PropertyInfo> properties, bool iterateSubModel) { var expando = new ExpandoObject() as IDictionary <string, object>; try { foreach (var property in properties) { if ((property.PropertyType.FullName.Contains("System.Collections.Generic.List") || property.PropertyType.FullName.Contains("System.Collections.Generic.IList")) && iterateSubModel) { var submodel = property.GetValue(modeltoConvert); if (submodel != null) { Type type = submodel.GetType().GetGenericArguments()[0]; //Type submodeltype = submodel.GetType(); var list = CreateListObject(submodel, type); var listResult = new List <IDictionary <string, object> >(); foreach (var itm in list) { var subproperties = DataTableExtensions.GetPropertiesForType <T>(type); listResult.Add(GenerateDBEntityFromProperty(itm, subproperties, iterateSubModel)); } var objname = GetAttributeName(property); expando.Add((objname == string.Empty ? property.Name.ToUpper() : objname), listResult); } } else if (property.PropertyType.FullName.Contains("GTS.BusinessEntity")) { var submodel = property.GetValue(modeltoConvert); if (submodel != null) { submodel = SetDefaultValuestoModels(submodel); Type submodeltype = submodel.GetType(); var subproperties = DataTableExtensions.GetPropertiesForType <T>(submodeltype); string attname = GetAttributeName(submodel); if (!string.IsNullOrEmpty(attname)) { expando.Add(attname.ToUpper(), GenerateDBEntityFromProperty(submodel, subproperties, iterateSubModel)); } else { //Recursive call for the sub models if (iterateSubModel) { expando.Add(property.Name.ToUpper(), GenerateDBEntityFromProperty(submodel, subproperties, iterateSubModel)); } } } } var att = property.GetCustomAttributes(true); ColumnAttribute p = null; if (att.Length > 0) { foreach (var itm in att) { if (typeof(ColumnAttribute).IsEquivalentTo(itm.GetType())) { p = itm as ColumnAttribute; if (p != null && !string.IsNullOrEmpty(p.FieldName)) { var val = property.GetValue(modeltoConvert); if (val != null && val.GetType() == typeof(bool) && p.IsNotBoolean) { expando.Add(p.FieldName.ToUpper(), (bool)val ? "Y" : "N"); } else if (val != null && val.GetType() == typeof(DateTime)) { expando.Add(p.FieldName.ToUpper(), ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss")); } else { expando.Add(p.FieldName.ToUpper(), val); } } } } } } return(expando); } catch (Exception ex) { return(expando); } }
// called when created from existing DBF file public void Initialize(DbfVersion version, FieldInfo fieldinfo, ColumnAttribute columnAttribute) { this.mFieldInfo = fieldinfo; this.mVersion = version; if (columnAttribute == null) columnAttribute = new ColumnAttribute(); Type fieldType = mFieldInfo.FieldType; if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>)) { IsNullable=true; NativeTypeCode= Type.GetTypeCode(fieldType.GetGenericArguments()[0]); } else this.NativeTypeCode = Type.GetTypeCode(fieldType); mColumnName = (columnAttribute.ColumnName == null || columnAttribute.ColumnName.Length == 0 ? fieldinfo.Name : columnAttribute.ColumnName); mColumnType = columnAttribute.Type; mWidth = columnAttribute.Width; mDecimals = columnAttribute.Decimals; int defaultWidth, defaultDecimals; if (mColumnType == ColumnType.UNKNOWN) { if (NativeTypeCode == TypeCode.Object) { GetDefaultColumnType(fieldType, mVersion, out mColumnType, out defaultWidth, out defaultDecimals); } else { GetDefaultColumnType(NativeTypeCode, IsNullable, mVersion, out mColumnType, out defaultWidth, out defaultDecimals); } if (mWidth == -1) mWidth = defaultWidth; if (mDecimals == -1) mDecimals = defaultDecimals; } CheckWidthAndDecimals(); }
public static bool TryGetColumnByPropertyName(String propertyName, out ColumnAttribute columnAttribute) { return(MetaData.Columns.TryGetValue(propertyName, out columnAttribute)); }