AutoInit.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using JLHHJSvr.LJException;
  2. using System;
  3. using System.Data.SqlClient;
  4. using System.Data.SqlTypes;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Web.UI.WebControls;
  9. namespace JLHHJSvr.Tools
  10. {
  11. public class AutoInit
  12. {
  13. public static void AutoInitS <T>(SqlCommand cmd, T instance){
  14. cmd.CommandText = @"SELECT COLUMN_NAME, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName";
  15. cmd.Parameters.Clear();
  16. cmd.Parameters.AddWithValue("@tableName", instance.GetType().Name);
  17. using (var reader = cmd.ExecuteReader())
  18. {
  19. while (reader.Read())
  20. {
  21. var column = Convert.ToString(reader["COLUMN_NAME"]).Trim();
  22. var isNullable = Convert.ToString(reader["IS_NULLABLE"]).Trim();
  23. var property = instance.GetType().GetProperties().FirstOrDefault(prop => prop.Name.Equals(column, StringComparison.OrdinalIgnoreCase));
  24. if(property == null)
  25. {
  26. //throw new LJCommonException($"数据库字段:{column}在模型中找不到相关属性!");
  27. continue;
  28. }
  29. if (isNullable.Equals("NO") && property.GetValue(instance) == null)
  30. {
  31. var type = property.PropertyType;
  32. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
  33. {
  34. type = type.GetGenericArguments()[0];
  35. }
  36. if (type.IsAssignableFrom(typeof(string)))
  37. {
  38. property.SetValue(instance, "");
  39. }
  40. else if (type.IsAssignableFrom(typeof(int))
  41. || type.IsAssignableFrom(typeof(decimal))
  42. || type.IsAssignableFrom(typeof(byte)))
  43. {
  44. property.SetValue(instance, Activator.CreateInstance(type));
  45. }
  46. }
  47. }
  48. }
  49. }
  50. public static void AutoInitS<T>(T instance)
  51. {
  52. foreach (var TB in instance.GetType().GetProperties())
  53. {
  54. var type = TB.PropertyType;
  55. var value = TB.GetValue(instance, null);
  56. if (value == null)
  57. {
  58. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
  59. {
  60. type = type.GetGenericArguments()[0];
  61. }
  62. if (type.IsAssignableFrom(typeof(string)))
  63. {
  64. value = string.Empty;
  65. }
  66. else if (type.IsAssignableFrom(typeof(int))
  67. || type.IsAssignableFrom(typeof(decimal))
  68. || type.IsAssignableFrom(typeof(byte)))
  69. {
  70. value = Activator.CreateInstance(type);
  71. }
  72. if (value != null)
  73. {
  74. TB.SetValue(instance, value, null);
  75. }
  76. }
  77. }
  78. }
  79. }
  80. }