private static void SetStruct(MDataColumn mdc, PropertyInfo pi, FieldInfo fi, int i, int count) { Type type = pi != null ? pi.PropertyType : fi.FieldType; string name = pi != null ? pi.Name : fi.Name; SqlDbType sqlType = SQL.DataType.GetSqlType(type); mdc.Add(name, sqlType); MCellStruct column = mdc[i]; LengthAttribute la = GetAttr <LengthAttribute>(pi, fi);//获取长度设置 if (la != null) { column.MaxSize = la.MaxSize; column.Scale = la.Scale; } if (column.MaxSize <= 0) { column.MaxSize = DataType.GetMaxSize(sqlType); } KeyAttribute ka = GetAttr <KeyAttribute>(pi, fi);//获取关键字判断 if (ka != null) { column.IsPrimaryKey = ka.IsPrimaryKey; column.IsAutoIncrement = ka.IsAutoIncrement; column.IsCanNull = ka.IsCanNull; } else if (i == 0) { column.IsPrimaryKey = true; column.IsCanNull = false; if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt)) { column.IsAutoIncrement = true; } } DefaultValueAttribute dva = GetAttr <DefaultValueAttribute>(pi, fi); if (dva != null && dva.DefaultValue != null) { if (column.SqlType == SqlDbType.Bit) { column.DefaultValue = (dva.DefaultValue.ToString() == "True" || dva.DefaultValue.ToString() == "1") ? 1 : 0; } else { column.DefaultValue = dva.DefaultValue; } } else if (i > count - 3 && sqlType == SqlDbType.DateTime && name.EndsWith("Time")) { column.DefaultValue = SqlValue.GetDate; } DescriptionAttribute da = GetAttr <DescriptionAttribute>(pi, fi);//看是否有字段描述属性。 if (da != null) { column.Description = da.Description; } }
public static MDataColumn GetColumns(Type typeInfo) { string key = "ColumnCache:" + typeInfo.FullName; if (columnCache.ContainsKey(key)) { return(columnCache[key].Clone()); } else { #region 获取列结构 MDataColumn mdc = new MDataColumn(); switch (StaticTool.GetSystemType(ref typeInfo)) { case SysType.Base: case SysType.Enum: mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false); return(mdc); case SysType.Generic: case SysType.Collection: Type[] argTypes; Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes); foreach (Type type in argTypes) { mdc.Add(type.Name, DataType.GetSqlType(type), false); } argTypes = null; return(mdc); } PropertyInfo[] pis = StaticTool.GetPropertyInfo(typeInfo); SqlDbType sqlType; for (int i = 0; i < pis.Length; i++) { sqlType = SQL.DataType.GetSqlType(pis[i].PropertyType); mdc.Add(pis[i].Name, sqlType); MCellStruct column = mdc[i]; column.MaxSize = DataType.GetMaxSize(sqlType); if (i == 0) { column.IsPrimaryKey = true; column.IsCanNull = false; if (column.ColumnName.ToLower().Contains("id") && (column.SqlType == System.Data.SqlDbType.Int || column.SqlType == SqlDbType.BigInt)) { column.IsAutoIncrement = true; } } else if (i > pis.Length - 3 && sqlType == SqlDbType.DateTime && pis[i].Name.EndsWith("Time")) { column.DefaultValue = SqlValue.GetDate; } } pis = null; #endregion if (!columnCache.ContainsKey(key)) { columnCache.Add(typeInfo.FullName, mdc.Clone()); } return(mdc); } }