private string GetAttributes(ColumnInfoModel c, Type csType) { TypeCode typeCode = Type.GetTypeCode(csType); StringBuilder sb = new StringBuilder(); if (c.Length > 0 && typeCode == TypeCode.String) { sb.Append("length: " + c.Length + ", "); } if (c.Precision > 0) { if (csType.IsGenericType) { csType = Nullable.GetUnderlyingType(csType); } if (typeCode.In(TypeCode.Single, TypeCode.Double, TypeCode.Decimal)) { sb.Append("precision: " + c.Precision + ", "); } } if (sb.Length > 0) { sb.Insert(0, "[Validate(").Remove(sb.Length - 2, 2).Append(")]"); } if (c.AutoGenerate) { sb.Append("[AutoGenerate]"); } return(sb.ToString()); }
public ColumnInfoModel[] GetColumns(string tableName) { if (tableName.IsNullOrWhiteSpace()) { throw new ArgumentException("", nameof(tableName)); } string sql = @" SELECT t1.column_name AS 'Name', CONVERT(bit, t3.isnullable) AS 'Nullable', t1.data_type AS 'DbType', ISNULL(t1.character_maximum_length,-1) AS 'Length', ISNULL(t1.numeric_scale,0) AS 'Precision', ISNULL(t2.value, '') AS 'Description', CONVERT(bit,t3.colstat) AS 'AutoGenerate' FROM information_schema.columns t1 LEFT JOIN sys.extended_properties t2 ON t2.major_id=OBJECT_ID(t1.table_name) AND t2.minor_id=t1.ordinal_position AND t2.name='MS_Description' AND t2.class_desc='OBJECT_OR_COLUMN' LEFT JOIN syscolumns t3 ON t3.id=OBJECT_ID(t1.table_name) AND t3.name=t1.column_name WHERE t1.table_name=@p0"; DataTable dt = _db.GetDataTable(new SqlCommand(sql), new SqlParameter("@p0", tableName)); ColumnInfoModel[] result = new ColumnInfoModel[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { DataRow r = dt.Rows[i]; ColumnInfoModel col = new ColumnInfoModel(); foreach (var p in typeof(ColumnInfoModel).GetProperties()) { //bool 要convert p.SetValue(col, p.GetType() == typeof(bool) ? Convert.ToBoolean(r[p.Name]) : r[p.Name], null); } result[i] = col; } return(result); }