Master.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection.Emit;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Security.AccessControl;
  9. namespace SqlSugar
  10. {
  11. public partial class DynamicBuilder
  12. {
  13. internal List<PropertyMetadata> propertyAttr = new List<PropertyMetadata>();
  14. internal List<CustomAttributeBuilder> entityAttr = new List<CustomAttributeBuilder>();
  15. internal string entityName { get; set; }
  16. internal Type baseType = null;
  17. internal Type[] interfaces = null;
  18. internal SqlSugarProvider context;
  19. public DynamicBuilder(SqlSugarProvider context)
  20. {
  21. this.context = context;
  22. }
  23. public DynamicProperyBuilder CreateClass(string entityName, SugarTable table=null, Type baseType = null, Type[] interfaces = null,SplitTableAttribute splitTableAttribute=null)
  24. {
  25. this.baseType = baseType;
  26. this.interfaces = interfaces;
  27. this.entityName = entityName;
  28. if (table == null)
  29. {
  30. table = new SugarTable() { TableName = entityName };
  31. }
  32. this.entityAttr = new List<CustomAttributeBuilder>() { GetEntity(table) };
  33. if (splitTableAttribute != null)
  34. {
  35. this.entityAttr.Add(GetSplitEntityAttr(splitTableAttribute));
  36. }
  37. return new DynamicProperyBuilder() { baseBuilder=this};
  38. }
  39. public object CreateObjectByType(Type type, Dictionary<string, object> dict)
  40. {
  41. // 创建一个默认的空对象
  42. object obj = Activator.CreateInstance(type);
  43. // 遍历字典中的每个 key-value 对
  44. foreach (KeyValuePair<string, object> pair in dict)
  45. {
  46. // 获取对象中的属性
  47. PropertyInfo propertyInfo = type.GetProperty(pair.Key);
  48. if (propertyInfo == null)
  49. {
  50. propertyInfo = type.GetProperties().FirstOrDefault(it=>it.Name.EqualCase(pair.Key));
  51. }
  52. if (propertyInfo != null)
  53. {
  54. propertyInfo.SetValue(obj, UtilMethods.ChangeType2(pair.Value, propertyInfo.PropertyType));
  55. }
  56. }
  57. // 返回创建的对象
  58. return obj;
  59. }
  60. public List<object> CreateObjectByType(Type type, List<Dictionary<string, object>> dictList)
  61. {
  62. List<object> result = new List<object>();
  63. foreach (var item in dictList)
  64. {
  65. result.Add(CreateObjectByType(type, item));
  66. }
  67. return result;
  68. }
  69. }
  70. }