using JLHHJSvr.LJException; using System; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; using System.Linq; using System.Text; using System.Web.UI.WebControls; namespace JLHHJSvr.Tools { public class AutoInit { public static void AutoInitS (SqlCommand cmd, T instance){ cmd.CommandText = @"SELECT COLUMN_NAME, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@tableName", instance.GetType().Name); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var column = Convert.ToString(reader["COLUMN_NAME"]).Trim(); var isNullable = Convert.ToString(reader["IS_NULLABLE"]).Trim(); var property = instance.GetType().GetProperties().FirstOrDefault(prop => prop.Name.Equals(column, StringComparison.OrdinalIgnoreCase)); if(property == null) { //throw new LJCommonException($"数据库字段:{column}在模型中找不到相关属性!"); continue; } if (isNullable.Equals("NO") && property.GetValue(instance) == null) { var type = property.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } if (type.IsAssignableFrom(typeof(string))) { property.SetValue(instance, ""); } else if (type.IsAssignableFrom(typeof(int)) || type.IsAssignableFrom(typeof(decimal)) || type.IsAssignableFrom(typeof(byte))) { property.SetValue(instance, Activator.CreateInstance(type)); } } } } } public static void AutoInitS(T instance) { foreach (var TB in instance.GetType().GetProperties()) { var type = TB.PropertyType; var value = TB.GetValue(instance, null); if (value == null) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } if (type.IsAssignableFrom(typeof(string))) { value = string.Empty; } else if (type.IsAssignableFrom(typeof(int)) || type.IsAssignableFrom(typeof(decimal)) || type.IsAssignableFrom(typeof(byte))) { value = Activator.CreateInstance(type); } if (value != null) { TB.SetValue(instance, value, null); } } } } } }