ConvertToDataTable.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.Data;
  7. using System.Collections;
  8. namespace Bowin.Common.Data
  9. {
  10. public static partial class ConvertToDataTable
  11. {
  12. /// <summary>
  13. /// 用来得到结果集,支持往下一层数据,但只有一层,下一层所有方法中是类属性都排除掉。
  14. /// </summary>
  15. /// <param name="source"></param>
  16. /// <param name="sachmaEquelDBTable">转换结构是否和数据库表相同,如果相同这去掉导航属性的信息。</param>
  17. /// <returns></returns>
  18. //[Obsolete("该方法只限于高级用途,支持特殊功能的需要,日常使用应该避免")]
  19. public static DataTable ToTable<T>(this IEnumerable<T> source, bool sachmaEquelDBTable = false)
  20. {
  21. DataTable dt = new DataTable("dataResult");
  22. //ArrayList al = new ArrayList(source.ToArray());
  23. //var al = source.ToList();
  24. var al = source.AsQueryable().ToList();
  25. getTableColomns<T>(ref dt, sachmaEquelDBTable);
  26. if (al.Count > 0)
  27. {
  28. getTableRows(al, ref dt, sachmaEquelDBTable);
  29. }
  30. return dt;
  31. }
  32. /// <summary>
  33. /// 用来得到结果集,支持往下一层数据,但只有一层,下一层所有方法中是类属性都排除掉。
  34. /// </summary>
  35. /// <param name="source"></param>
  36. /// <param name="sachmaEquelDBTable">转换结构是否和数据库表相同,如果相同这去掉导航属性的信息。</param>
  37. /// <returns></returns>
  38. //[Obsolete("该方法只限于高级用途,支持特殊功能的需要,日常使用应该避免")]
  39. public static DataTable ToTable<T>(this IEnumerable<T> source, IList<string> columnNameList)
  40. {
  41. DataTable dt = new DataTable("dataResult");
  42. //ArrayList al = new ArrayList(source.ToArray());
  43. //var al = source.ToList();
  44. var al = source.AsQueryable().ToList();
  45. getTableColumns<T>(ref dt, columnNameList);
  46. if (al.Count > 0)
  47. {
  48. getTableRows(al, ref dt, columnNameList);
  49. }
  50. return dt;
  51. }
  52. private static void getTableColumns<T>(ref DataTable dt, IList<string> columnNameList)
  53. {
  54. Type t = typeof(T);
  55. if (!t.IsClass)
  56. {
  57. return;
  58. }
  59. System.Reflection.PropertyInfo[] properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  60. foreach (var columnName in columnNameList)
  61. {
  62. var columnNameParts = columnName.Split('.').Where(x => !string.IsNullOrEmpty(x)).ToList();
  63. if (columnNameParts.Count == 0)
  64. {
  65. continue;
  66. }
  67. var property = properties.FirstOrDefault(x => x.Name == columnNameParts[0]);
  68. if (property == null)
  69. {
  70. continue;
  71. }
  72. bool isFind = true;
  73. for (int i = 1; i < columnNameParts.Count; i++)
  74. {
  75. var propertyType = property.PropertyType;
  76. PropertyInfo[] itemProperties = propertyType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  77. var itemProperty = itemProperties.FirstOrDefault(x => x.Name == columnNameParts[i]);
  78. if (itemProperty == null)
  79. {
  80. isFind = false;
  81. break;
  82. }
  83. property = itemProperty;
  84. }
  85. if (isFind && !dt.Columns.Contains(columnName))
  86. {
  87. dt.Columns.Add(columnName, getOjectTypeOrDefault(property));
  88. }
  89. }
  90. }
  91. private static void getTableColomns<T>(ref DataTable dt, bool sachmaEquelDBTable = false)
  92. {
  93. Type t = typeof(T);
  94. if (t.IsClass)
  95. {
  96. System.Reflection.PropertyInfo[] properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  97. foreach (PropertyInfo item in properties)
  98. {
  99. if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
  100. {
  101. if (!dt.Columns.Contains(item.Name))
  102. {
  103. dt.Columns.Add(item.Name, getOjectTypeOrDefault(item));
  104. }
  105. }
  106. else
  107. {
  108. if (sachmaEquelDBTable)
  109. {
  110. continue;
  111. }
  112. Type t1 = item.PropertyType;
  113. System.Reflection.PropertyInfo[] Itemproperties = t1.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  114. foreach (PropertyInfo detid in Itemproperties)
  115. {
  116. if (detid is ICollection)
  117. {
  118. continue;
  119. }
  120. if (detid.PropertyType.IsValueType || detid.PropertyType.Name.StartsWith("String"))
  121. {
  122. if (!dt.Columns.Contains(detid.Name))
  123. {
  124. dt.Columns.Add(detid.Name, getOjectTypeOrDefault(detid));
  125. }
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }
  132. private static void getTableRows<T>(List<T> Sources, ref DataTable dt, IList<string> columnNameList)
  133. {
  134. foreach (object source in Sources)
  135. {
  136. Type t = source.GetType();
  137. DataRow cdr = dt.NewRow();
  138. if (t.IsClass)
  139. {
  140. var properties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  141. foreach (var columnName in columnNameList)
  142. {
  143. var columnNameParts = columnName.Split('.').Where(x => !string.IsNullOrEmpty(x)).ToList();
  144. if (columnNameParts.Count == 0)
  145. {
  146. continue;
  147. }
  148. var property = properties.FirstOrDefault(x => x.Name == columnNameParts[0]);
  149. if (property == null)
  150. {
  151. continue;
  152. }
  153. var propertyValue = property.GetValue(source, null);
  154. bool isFind = true;
  155. for (int i = 1; i < columnNameParts.Count; i++)
  156. {
  157. var propertyType = property.PropertyType;
  158. PropertyInfo[] itemProperties = propertyType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  159. var itemProperty = itemProperties.FirstOrDefault(x => x.Name == columnNameParts[i]);
  160. if (itemProperty == null)
  161. {
  162. isFind = false;
  163. break;
  164. }
  165. property = itemProperty;
  166. propertyValue = itemProperty.GetValue(propertyValue, null);
  167. }
  168. if (isFind && dt.Columns.Contains(columnName))
  169. {
  170. cdr[columnName] = propertyValue;
  171. }
  172. }
  173. dt.Rows.Add(cdr);
  174. }
  175. }
  176. }
  177. private static void getTableRows<T>(List<T> Sources, ref DataTable dt, bool sachmaEquelDBTable = false)
  178. {
  179. foreach (object source in Sources)
  180. {
  181. Type t = source.GetType();
  182. DataRow cdr = dt.NewRow();
  183. if (t.IsClass)
  184. {
  185. foreach (PropertyInfo item in
  186. t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  187. {
  188. if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
  189. {
  190. cdr[item.Name] = getOjectValueOrDefault(source, item);
  191. }
  192. else
  193. {
  194. if (sachmaEquelDBTable)
  195. {
  196. continue;
  197. }
  198. object objEnd = item.GetValue(source, null);
  199. if (objEnd == null)
  200. {
  201. continue;
  202. }
  203. Type t1 = objEnd.GetType();
  204. foreach (PropertyInfo detid in t1.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  205. {
  206. if (detid.PropertyType.IsValueType || detid.PropertyType.Name.StartsWith("String"))
  207. {
  208. cdr[detid.Name] = getOjectValueOrDefault(objEnd, detid);
  209. }
  210. }
  211. }
  212. }
  213. dt.Rows.Add(cdr);
  214. }
  215. }
  216. }
  217. public static DataTable ConvertToTable<T>(IEnumerable<T> source, string TableName = "dataResult", bool sachmaEquelDBTable = false)
  218. {
  219. DataTable dt = new DataTable(TableName);
  220. var al = source.AsQueryable().ToList();
  221. getTableColomns<T>(ref dt, sachmaEquelDBTable);
  222. if (al.Count > 0)
  223. {
  224. getTableRows(al, ref dt, sachmaEquelDBTable);
  225. }
  226. return dt;
  227. }
  228. public static IDictionary<Type, string> _SqlDbTypeConvertor = new Dictionary<Type, string>();
  229. public static IDictionary<Type, string> SqlDbTypeConvertor
  230. {
  231. get
  232. {
  233. if (_SqlDbTypeConvertor.Count == 0)
  234. {
  235. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Int32), "int"));
  236. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Int32>), "int"));
  237. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Int64), "bigint"));
  238. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Int64>), "bigint"));
  239. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Boolean), "bit"));
  240. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Boolean>), "bit"));
  241. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(string), "nvarchar(max)"));
  242. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(DateTime), "datetime2(7)"));
  243. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<DateTime>), "datetime2(7)"));
  244. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(DateTimeOffset), "datetimeoffset(7)"));
  245. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<DateTimeOffset>), "datetimeoffset(7)"));
  246. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(decimal), "decimal(23,2)"));
  247. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<decimal>), "decimal(23,2)"));
  248. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Double), "float"));
  249. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Double>), "float"));
  250. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Int16), "smallint"));
  251. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Int16>), "smallint"));
  252. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Byte), "tinyint"));
  253. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Byte>), "tinyint"));
  254. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Guid), "uniqueidentifier"));
  255. _SqlDbTypeConvertor.Add(new KeyValuePair<Type, string>(typeof(Nullable<Guid>), "uniqueidentifier"));
  256. }
  257. return _SqlDbTypeConvertor;
  258. }
  259. }
  260. private static Type getOjectTypeOrDefault(PropertyInfo pinfo)
  261. {
  262. if (!pinfo.PropertyType.Name.StartsWith("Nullable"))
  263. {
  264. return pinfo.PropertyType;
  265. }
  266. else
  267. {
  268. Type t = pinfo.PropertyType;
  269. Type rT = typeof(Nullable);
  270. System.Reflection.PropertyInfo Itempropertie = t.GetProperty("Value");
  271. rT = Itempropertie.PropertyType;
  272. return rT;
  273. }
  274. }
  275. private static object getOjectValueOrDefault(object oparent, PropertyInfo pinfo)
  276. {
  277. object result = new object();
  278. if (!pinfo.PropertyType.Name.StartsWith("Nullable"))
  279. {
  280. result = pinfo.GetValue(oparent, null);
  281. }
  282. else
  283. {
  284. System.Reflection.PropertyInfo Itempropertie = pinfo.PropertyType.GetProperty("Value");
  285. object item = pinfo.GetValue(oparent, null);
  286. if (item == null)
  287. {
  288. result = DBNull.Value;
  289. }
  290. else
  291. {
  292. object ip = Itempropertie.GetValue(item, null);
  293. result = ip == null ? DBNull.Value : ip;
  294. }
  295. }
  296. return result;
  297. }
  298. /// <summary>
  299. /// 将数据行转换成实体
  300. /// </summary>
  301. /// <param name="row">要转换的数据行</param>
  302. /// <returns>实体</returns>
  303. public static TEntity GetEntityByDataRow<TEntity>(System.Data.DataRow row)
  304. {
  305. int i;
  306. TEntity entity;
  307. Type entityType = typeof(TEntity);
  308. System.Reflection.PropertyInfo[] properties = entityType.GetProperties();
  309. entity = (TEntity)Assembly.GetAssembly(entityType).CreateInstance(entityType.FullName, false);
  310. try
  311. {
  312. for (i = 0; i < properties.Length; i++)
  313. {
  314. if (properties[i].PropertyType.IsPrimitive || properties[i].PropertyType.IsValueType || properties[i].PropertyType.Name.StartsWith("String"))
  315. {
  316. if ((row[properties[i].Name] ?? properties[i].PropertyType.Assembly.CreateInstance(properties[i].PropertyType.FullName)) == null)
  317. {
  318. continue;
  319. }
  320. if (row[properties[i].Name] == DBNull.Value)
  321. {
  322. if (properties[i].PropertyType.Name.StartsWith("String"))
  323. {
  324. continue;
  325. }
  326. properties[i].SetValue(
  327. entity, properties[i].PropertyType.Assembly.CreateInstance(properties[i].PropertyType.FullName), null);
  328. }
  329. else
  330. {
  331. properties[i].SetValue(
  332. entity, row[properties[i].Name], null);
  333. }
  334. }
  335. }
  336. return entity;
  337. }
  338. catch
  339. {
  340. return default(TEntity);
  341. }
  342. }
  343. }
  344. }