DataToModel.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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 Ant.Frame;
  8. using System.Data.SqlClient;
  9. using System.Linq.Expressions;
  10. using System.ComponentModel;
  11. using System.Collections;
  12. namespace Ant.ORM
  13. {
  14. public static class DataToModel
  15. {
  16. #region 将DataTable转换成List列表
  17. #region 返回一条实体数据
  18. /// <summary>
  19. /// DataReader转实体
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. /// <param name="rdr"></param>
  23. /// <returns></returns>
  24. public static T Dr2En<T>(IDataReader rdr) where T : class
  25. {
  26. DataTable dtt = Dr2Dt(rdr);
  27. return Dt2En<T>(dtt); ;
  28. }
  29. public static T Dr2En<T>(IDataReader rdr, object enty) where T : class
  30. {
  31. DataTable dtt = Dr2Dt(rdr);
  32. return Dt2En<T>(dtt, enty); ;
  33. }
  34. /// <summary>
  35. /// DataReader转Object
  36. /// </summary>
  37. /// <param name="rdr"></param>
  38. /// <param name="entity"></param>
  39. /// <returns></returns>
  40. public static T Dr2EnObj<T>(IDataReader rdr, T entity) where T : class
  41. {
  42. DataTable dtt = Dr2Dt(rdr);
  43. return Dt2EnObj<T>(dtt, entity);
  44. }
  45. /// <summary>
  46. /// 返回一条实体数据
  47. /// </summary>
  48. /// <typeparam name="T">实体</typeparam>
  49. /// <param name="dataTable">表数据</param>
  50. /// <returns></returns>
  51. public static T Dt2En<T>(DataTable dataTable) where T : class
  52. {
  53. T obj = default(T);
  54. if (dataTable.Rows.Count > 0)
  55. {
  56. var md = MetaDataManager.GetMetaData(typeof(T));
  57. obj = Activator.CreateInstance<T>();
  58. DataRow row = dataTable.Rows[0];
  59. obj = DtSetValueFieldOld(row, obj, md) as T;
  60. }
  61. return obj;
  62. }
  63. /// <summary>
  64. /// 返回一条实体数据
  65. /// </summary>
  66. /// <typeparam name="T">实体</typeparam>
  67. /// <param name="dataTable">表数据</param>
  68. /// <returns></returns>
  69. public static T Dt2En<T>(DataTable dataTable, object enty) where T : class
  70. {
  71. var md = MetaDataManager.GetMetaData(enty.GetType());
  72. T obj = Activator.CreateInstance<T>();
  73. obj = enty as T;
  74. if (dataTable.Rows.Count > 0)
  75. {
  76. DataRow row = dataTable.Rows[0];
  77. obj = DtSetValueFieldOld(row, obj, md) as T;
  78. }
  79. return obj;
  80. }
  81. /// <summary>
  82. /// 返回一条实体数据
  83. /// </summary>
  84. /// <typeparam name="T">实体</typeparam>
  85. /// <param name="dataTable">表数据</param>
  86. /// <returns></returns>
  87. public static object Dt2EnObj<T>(DataTable dt) where T : class
  88. {
  89. var md = MetaDataManager.GetMetaData(typeof(T));
  90. T obj = Activator.CreateInstance<T>();
  91. if (dt.Rows.Count > 0)
  92. {
  93. DataRow row = dt.Rows[0];
  94. obj = DtSetValueFieldOld(row, obj, md) as T;
  95. }
  96. return obj;
  97. }
  98. /// <summary>
  99. /// 获取一条实体
  100. /// </summary>
  101. /// <param name="dt"></param>
  102. /// <param name="enty"></param>
  103. /// <returns></returns>
  104. public static T Dt2EnObj<T>(DataTable dt, T enty) where T : class
  105. {
  106. var md = MetaDataManager.GetMetaData(enty.GetType());
  107. T obj = Activator.CreateInstance(md.EntityType) as T;
  108. if (dt == null) return obj;
  109. if (dt.Rows.Count == 0) return obj;
  110. DataRow dr = dt.Rows[0];
  111. obj = (T)DtSetValueFieldOld(dr, obj, md);
  112. return obj;
  113. }
  114. #endregion
  115. #region 返回实体集合
  116. /// <summary>
  117. /// DataReader转object
  118. /// </summary>
  119. /// <param name="rdr"></param>
  120. /// <param name="entity"></param>
  121. /// <returns></returns>
  122. public static List<T> Dr2EnList<T>(IDataReader rdr, T entity) where T : class
  123. {
  124. DataTable dtt = Dr2Dt(rdr);
  125. return Dt2EnList<T>(dtt, entity);
  126. }
  127. /// <summary>
  128. /// DataReader转实体集合
  129. /// </summary>
  130. /// <typeparam name="T"></typeparam>
  131. /// <param name="rdr"></param>
  132. /// <returns></returns>
  133. public static List<T> Dr2EnList<T>(IDataReader rdr)
  134. {
  135. DataTable dtt = Dr2Dt(rdr);
  136. List<T> listobj = Dt2EnList<T>(dtt);
  137. return listobj;
  138. }
  139. /// <summary>
  140. /// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
  141. /// </summary>
  142. /// <typeparam name="T"></typeparam>
  143. /// <param name="dt"></param>
  144. /// <returns></returns>
  145. public static List<T> Dt2EnList<T>(DataTable dt)
  146. {
  147. List<T> list = new List<T>();
  148. var md = MetaDataManager.GetMetaData(typeof(T));
  149. if (dt == null) return list;
  150. foreach (DataRow row in dt.Rows)
  151. {
  152. T obj = Activator.CreateInstance<T>();
  153. obj = (T)DtSetValueField(row, obj, md);
  154. list.Add(obj);
  155. }
  156. return list;
  157. }
  158. /// <summary>
  159. /// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
  160. /// </summary>
  161. /// <typeparam name="T"></typeparam>
  162. /// <param name="dt"></param>
  163. /// <returns></returns>
  164. public static List<T> Dt2EnList<T>(T obj, DataTable dt) where T : class
  165. {
  166. List<T> list = new List<T>();
  167. if (dt == null) return list;
  168. var md = MetaDataManager.GetMetaData(typeof(T));
  169. foreach (DataRow row in dt.Rows)
  170. {
  171. T objj = obj;
  172. objj = DtSetValueField(row, objj, md) as T;
  173. list.Add(objj);
  174. }
  175. return list;
  176. }
  177. /// <summary>
  178. /// DataTable转换成实体列表此方法是实体属性不带?的可以这样转换
  179. /// </summary>
  180. /// <typeparam name="T">实体 T </typeparam>
  181. /// <param name="table">datatable</param>
  182. /// <returns></returns>
  183. public static IList<T> DtToList<T>(DataTable table)
  184. where T : class
  185. {
  186. IList<T> list = new List<T>();
  187. if (!table.IsHaveRows()) return list;
  188. T model = default(T);
  189. foreach (DataRow dr in table.Rows)
  190. {
  191. model = Activator.CreateInstance<T>();
  192. foreach (DataColumn dc in dr.Table.Columns)
  193. {
  194. object drValue = dr[dc.ColumnName];
  195. PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName,
  196. BindingFlags.Public | BindingFlags.NonPublic
  197. | BindingFlags.Instance | BindingFlags.IgnoreCase);
  198. if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
  199. {
  200. pi.SetValue(model, drValue, null);
  201. }
  202. }
  203. list.Add(model);
  204. }
  205. return list;
  206. }
  207. /// <summary>
  208. /// 将表数据转换成实体集合
  209. /// </summary>
  210. /// <param name="dataTable">表数据</param>
  211. /// <param name="enty">实体</param>
  212. /// <returns></returns>
  213. public static List<T> Dt2EnList<T>(DataTable dt, T enty) where T : class
  214. {
  215. List<T> list = new List<T>();
  216. if (!dt.IsHaveRows()) return list;
  217. var md = MetaDataManager.GetMetaData(typeof(T));
  218. foreach (DataRow row in dt.Rows)
  219. {
  220. T obj = Activator.CreateInstance(enty.GetType()) as T;
  221. obj = (T)DtSetValueFieldOld(row, obj, md);
  222. list.Add(obj);
  223. }
  224. return list;
  225. }
  226. #endregion
  227. #region 公共调用用DataRow给实体进行赋值
  228. public static List<T> ReaderToList<T>(IDataReader dr)
  229. {
  230. using (dr)
  231. {
  232. var md = MetaDataManager.GetMetaData(typeof(T));
  233. List<string> list = new List<string>(dr.FieldCount);
  234. for (int i = 0; i < dr.FieldCount; i++)
  235. {
  236. list.Add(dr.GetName(i).ToLower());
  237. }
  238. List<T> list2 = new List<T>();
  239. while (dr.Read())
  240. {
  241. T local = Activator.CreateInstance<T>();
  242. foreach (PropertyInfo info in md.Propertys)
  243. {
  244. if (list.Contains(info.Name.ToLower()) && !IsNullOrDBNull(dr[info.Name]))
  245. {
  246. info.SetValue(local, HackType(dr[info.Name], info.PropertyType), null);
  247. }
  248. }
  249. list2.Add(local);
  250. }
  251. return list2;
  252. }
  253. }
  254. /// <summary>
  255. /// 给实体进行赋值
  256. /// </summary>
  257. /// <param name="row"></param>
  258. /// <param name="objj"></param>
  259. /// <returns></returns>
  260. private static object DtSetValueFieldOld(DataRow row, object objj, FiledMetaData md)
  261. {
  262. // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
  263. foreach (DataColumn dc in row.Table.Columns)
  264. {
  265. PropertyInfo pinfo = md.EntityType.GetProperty(dc.ColumnName.ToLower(),
  266. BindingFlags.Public | BindingFlags.NonPublic
  267. | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
  268. try
  269. {
  270. if (String.Compare(dc.ColumnName, "Version", true) == 0)
  271. {
  272. byte[] bts = (byte[])(row[dc.ColumnName]);
  273. Array.Reverse(bts);
  274. long num = BitConverter.ToInt64(bts, 0);
  275. pinfo.SetValue(objj, num, null);
  276. }
  277. else
  278. {
  279. object drValue = row[dc.ColumnName];
  280. if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
  281. {
  282. if (pinfo.PropertyType == typeof(Int64) || pinfo.PropertyType == typeof(Int64?))
  283. //if (pinfo.PropertyType.ToString().ToLower().Contains("system.int64"))
  284. pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
  285. else if (pinfo.PropertyType == typeof(Int32) || pinfo.PropertyType == typeof(Int32?))
  286. pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
  287. else if (pinfo.PropertyType == typeof(DateTime) || pinfo.PropertyType == typeof(DateTime?))
  288. pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
  289. else if (pinfo.PropertyType == typeof(Boolean) || pinfo.PropertyType == typeof(Boolean?))
  290. pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
  291. else if (pinfo.PropertyType == typeof(Single) || pinfo.PropertyType == typeof(Single?))
  292. pinfo.SetValue(objj, Convert.ToSingle(drValue), null);
  293. else if (pinfo.PropertyType == typeof(Double) || pinfo.PropertyType == typeof(Double?))
  294. pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
  295. else if (pinfo.PropertyType == typeof(Decimal) || pinfo.PropertyType == typeof(Decimal?))
  296. pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
  297. else if (pinfo.PropertyType == typeof(Guid) || pinfo.PropertyType == typeof(Guid?))
  298. pinfo.SetValue(objj, new Guid(drValue.ToString()), null);
  299. else if (pinfo.PropertyType == typeof(Byte) || pinfo.PropertyType == typeof(Byte?))
  300. pinfo.SetValue(objj, Convert.ToByte(drValue), null);
  301. else if (pinfo.PropertyType == typeof(SByte) || pinfo.PropertyType == typeof(SByte?))
  302. pinfo.SetValue(objj, Convert.ToSByte(drValue), null);
  303. else if (pinfo.PropertyType == typeof(Int16) || pinfo.PropertyType == typeof(Int16?))
  304. pinfo.SetValue(objj, Convert.ToInt16(drValue), null);
  305. else if (pinfo.PropertyType == typeof(Char) || pinfo.PropertyType == typeof(Char?))
  306. pinfo.SetValue(objj, Convert.ToChar(drValue), null);
  307. else
  308. pinfo.SetValue(objj, drValue, null);
  309. #region 旧版本
  310. #region Compare是比较相等
  311. //if (string.Compare(pinfo.PropertyType.ToString(), "system.int32", true) == 0)
  312. // pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
  313. //else if (string.Compare(pinfo.PropertyType.ToString(), "system.int64", true) == 0)
  314. // pinfo.SetValue(objj, Convert.ToInt64(drValue), null);
  315. //else if (string.Compare(pinfo.PropertyType.ToString(), "system.boolean", true) == 0)
  316. // pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
  317. //else if (string.Compare(pinfo.PropertyType.ToString(), "system.datetime", true) == 0)
  318. // pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
  319. //else if (string.Compare(pinfo.PropertyType.ToString(), "system.decimal", true) == 0)
  320. // pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
  321. //else if (string.Compare(pinfo.PropertyType.ToString(), "system.double", true) == 0)
  322. // pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
  323. //else
  324. // pinfo.SetValue(objj, drValue, null);
  325. #endregion
  326. #region 不用了
  327. //switch (pinfo.PropertyType.ToString().ToLower())
  328. //{
  329. // case "system.int32":
  330. // pinfo.SetValue(objj, Convert.ToInt32(drValue), null);
  331. // break;
  332. // case "system.boolean":
  333. // pinfo.SetValue(objj, Convert.ToBoolean(drValue), null);
  334. // break;
  335. // case "system.datetime":
  336. // pinfo.SetValue(objj, Convert.ToDateTime(drValue), null);
  337. // break;
  338. // case "system.decimal":
  339. // pinfo.SetValue(objj, Convert.ToDecimal(drValue), null);
  340. // break;
  341. // case "system.double":
  342. // pinfo.SetValue(objj, Convert.ToDouble(drValue), null);
  343. // break;
  344. // default:
  345. // pinfo.SetValue(objj, drValue, null);
  346. // break;
  347. //}
  348. #endregion
  349. #region 另一种实现
  350. //另一种在一定条件可以实现的方法
  351. //pinfo.SetValue(objj, Convert.ChangeType(drValue, pinfo.PropertyType), null);
  352. //如果实体中带?的时就不能用这种方式,实体中带?是代表可空,实体作为查询条件的时候必须把值类型加?
  353. //这样实例的时候就默认为Null,实体中带?就用上面那种强制转换;
  354. #endregion
  355. #endregion
  356. }
  357. else
  358. {
  359. if (pinfo != null && pinfo.CanWrite)
  360. pinfo.SetValue(objj, null, null);
  361. }
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. pinfo.SetValue(objj, null, null);
  367. }
  368. }
  369. PropertyInfo pi = md.EntityType.GetProperty("PersistType",
  370. BindingFlags.Public | BindingFlags.NonPublic
  371. | BindingFlags.Instance | BindingFlags.IgnoreCase);
  372. if (pi != null && pi.CanWrite)
  373. pi.SetValue(objj, EntityPersistType.Update, null);
  374. return objj;
  375. }
  376. /// <summary>
  377. /// 给实体进行赋值
  378. /// </summary>
  379. /// <param name="row"></param>
  380. /// <param name="objj"></param>
  381. /// <returns></returns>
  382. private static T DtSetValueField<T>(DataRow row, T objj, FiledMetaData md)
  383. {
  384. // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
  385. foreach (DataColumn dc in row.Table.Columns)
  386. {
  387. PropertyInfo pinfo = md.EntityType.GetProperty(dc.ColumnName.ToLower(),
  388. BindingFlags.Public | BindingFlags.NonPublic
  389. | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
  390. //PropertyInfo pinfo = objj.GetType().GetProperty(dc.ColumnName.ToLower(),
  391. // BindingFlags.Public | BindingFlags.NonPublic
  392. // | BindingFlags.Instance | BindingFlags.IgnoreCase);//这种如何实现有待解决,现在解决方法就是将实体属性的标签的名称和实体名称大写完全一样,这样才能保证这边不报错
  393. try
  394. {
  395. if (String.Compare(dc.ColumnName, "Version", true) == 0)//给时间戳赋值
  396. {
  397. byte[] bts = (byte[])(row[dc.ColumnName]);
  398. Array.Reverse(bts);
  399. long num = BitConverter.ToInt64(bts, 0);
  400. pinfo.SetValue(objj, num, null);
  401. }
  402. else
  403. {
  404. object drValue = row[dc.ColumnName];
  405. if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
  406. {
  407. if (!pinfo.PropertyType.IsGenericType)
  408. {
  409. //非泛型
  410. pinfo.SetValue(objj, Convert.ChangeType(drValue, pinfo.PropertyType), null);
  411. }
  412. else
  413. {
  414. //泛型Nullable<>
  415. Type genericTypeDefinition = pinfo.PropertyType.GetGenericTypeDefinition();
  416. if (genericTypeDefinition == typeof(Nullable<>))
  417. {
  418. pinfo.SetValue(objj, Convert.ChangeType(drValue, Nullable.GetUnderlyingType(pinfo.PropertyType)), null);
  419. }
  420. }
  421. }
  422. else
  423. {
  424. if (pinfo != null && pinfo.CanWrite)
  425. pinfo.SetValue(objj, null, null);
  426. }
  427. }
  428. }
  429. catch (Exception ex)
  430. {
  431. pinfo.SetValue(objj, null, null);
  432. }
  433. }
  434. PropertyInfo pi = md.EntityType.GetProperty("PersistType",
  435. BindingFlags.Public | BindingFlags.NonPublic
  436. | BindingFlags.Instance | BindingFlags.IgnoreCase);
  437. if (pi != null && pi.CanWrite)
  438. pi.SetValue(objj, EntityPersistType.Update, null);
  439. return objj;
  440. }
  441. /// <summary>
  442. /// 给牧举赋值
  443. /// </summary>
  444. /// <typeparam name="T"></typeparam>
  445. /// <param name="value"></param>
  446. /// <param name="ordinal"></param>
  447. /// <returns></returns>
  448. public static T GetEnum<T>(object value) where T : struct
  449. {
  450. T t = (T)Enum.ToObject(typeof(T), value);
  451. return t;
  452. }
  453. /// <summary>
  454. /// 可空牧举赋值
  455. /// </summary>
  456. /// <typeparam name="T"></typeparam>
  457. /// <param name="value"></param>
  458. /// <param name="ordinal"></param>
  459. /// <returns></returns>
  460. public static T? GetEnum_Nullable<T>(object value, int ordinal) where T : struct
  461. {
  462. if (value.IsNull())
  463. {
  464. return null;
  465. }
  466. else
  467. {
  468. T t = (T)Enum.ToObject(typeof(T), value);
  469. return t;
  470. }
  471. }
  472. /// <summary>
  473. /// 调用说明:
  474. /// int intValue1 = "123".ConvertTo<int>();
  475. /// int? intValue2 = "123".ConvertTo<int?>();
  476. /// DateTime dateTimeValue1 = "1981-08-24".ConvertTo<DateTime>();
  477. /// DateTime? dateTimeValue2 = "1981-08-24".ConvertTo<DateTime?>();
  478. /// </summary>
  479. /// <typeparam name="T"></typeparam>
  480. /// <param name="convertibleValue"></param>
  481. /// <returns></returns>
  482. public static T ConvertTo<T>(this IConvertible convertibleValue)
  483. {
  484. if (null == convertibleValue)
  485. {
  486. return default(T);
  487. }
  488. if (!typeof(T).IsGenericType)
  489. {
  490. return (T)Convert.ChangeType(convertibleValue, typeof(T));
  491. }
  492. else
  493. {
  494. Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
  495. if (genericTypeDefinition == typeof(Nullable<>))
  496. {
  497. return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
  498. }
  499. }
  500. throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".", convertibleValue.GetType().FullName, typeof(T).FullName));
  501. }
  502. /// <summary>
  503. /// 检查DataTable 是否有数据行
  504. /// </summary>
  505. /// <param name="dt">DataTable</param>
  506. /// <returns></returns>
  507. public static bool IsHaveRows(this DataTable dt)
  508. {
  509. if (dt != null && dt.Rows.Count > 0)
  510. return true;
  511. return false;
  512. }
  513. /// <summary>
  514. /// DataReader转DataTable
  515. /// </summary>
  516. /// <param name="rdr"></param>
  517. /// <returns></returns>
  518. public static DataTable Dr2Dt(IDataReader rdr)
  519. {
  520. DataTable dtReturn = new DataTable();
  521. DataColumn dc = null;
  522. DataRow dr = null;
  523. for (int i = 0; i < rdr.GetSchemaTable().Rows.Count; i++)
  524. {
  525. dr = rdr.GetSchemaTable().Rows[i];
  526. dc = new DataColumn(dr["ColumnName"].ToString(), dr["DataType"] as Type);
  527. if (!dtReturn.Columns.Contains(dr["ColumnName"].ToString()))
  528. {
  529. dtReturn.Columns.Add(dc);
  530. }
  531. }
  532. object[] value = new object[dtReturn.Columns.Count];
  533. while (rdr.Read())
  534. {
  535. rdr.GetValues(value);
  536. dtReturn.LoadDataRow(value, true);
  537. }
  538. return dtReturn;
  539. }
  540. /// <summary>
  541. ///
  542. /// </summary>
  543. /// <param name="dataReader"></param>
  544. /// <returns></returns>
  545. public static DataTable ConvertDataReaderToDataTable(IDataReader dataReader)
  546. {
  547. ///定义DataTable
  548. DataTable datatable = new DataTable();
  549. try
  550. { ///动态添加表的数据列
  551. for (int i = 0; i < dataReader.FieldCount; i++)
  552. {
  553. DataColumn myDataColumn = new DataColumn();
  554. myDataColumn.DataType = dataReader.GetFieldType(i);
  555. myDataColumn.ColumnName = dataReader.GetName(i);
  556. datatable.Columns.Add(myDataColumn);
  557. }
  558. ///添加表的数据
  559. while (dataReader.Read())
  560. {
  561. DataRow myDataRow = datatable.NewRow();
  562. for (int i = 0; i < dataReader.FieldCount; i++)
  563. {
  564. myDataRow[i] = dataReader[i].ToString();
  565. }
  566. datatable.Rows.Add(myDataRow);
  567. myDataRow = null;
  568. }
  569. ///关闭数据读取器
  570. dataReader.Close();
  571. return datatable;
  572. }
  573. catch (Exception ex)
  574. {
  575. ///抛出类型转换错误
  576. //SystemError.CreateErrorLog(ex.Message);
  577. throw new Exception(ex.Message, ex);
  578. }
  579. }
  580. /// <summary>
  581. /// DataReader转DataTable
  582. /// </summary>
  583. /// <param name="reader"></param>
  584. /// <returns></returns>
  585. public static DataTable ReaderToDataTable(IDataReader reader)
  586. {
  587. DataTable table = new DataTable("Table");
  588. int fieldCount = reader.FieldCount;
  589. for (int i = 0; i < fieldCount; i++)
  590. {
  591. table.Columns.Add(reader.GetName(i).ToLower(), reader.GetFieldType(i));
  592. }
  593. table.BeginLoadData();
  594. object[] values = new object[fieldCount];
  595. while (reader.Read())
  596. {
  597. reader.GetValues(values);
  598. table.LoadDataRow(values, true);
  599. }
  600. reader.Close();
  601. table.EndLoadData();
  602. return table;
  603. }
  604. #endregion
  605. #endregion
  606. #region 备份
  607. ///// <summary>
  608. ///// 给实体进行赋值
  609. ///// </summary>
  610. ///// <param name="row"></param>
  611. ///// <param name="objj"></param>
  612. ///// <returns></returns>
  613. //private static object DtSetValueField(DataRow row, object objj)
  614. //{
  615. // Dictionary<string, EntityValue> vl = new Dictionary<string, EntityValue>();
  616. // foreach (PropertyInfo pinfo in objj.GetType().GetProperties())
  617. // {
  618. // DataFieldColumnAttribute dfa = Attribute.GetCustomAttribute(pinfo, typeof(DataFieldColumnAttribute)) as DataFieldColumnAttribute;
  619. // if (!object.Equals(dfa, null))
  620. // {
  621. // try
  622. // {
  623. // //if (!Convert.IsDBNull(row[pinfo.Name]))
  624. // object drValue = row[pinfo.Name];
  625. // if (pinfo != null && pinfo.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
  626. // {
  627. // vl = SetChanaged(pinfo.Name, row[pinfo.Name], vl);
  628. // #region 备份暂时不用
  629. // //if (pinfo.PropertyType.ToString().ToLower().Contains("system.int64"))
  630. // // pinfo.SetValue(objj, Convert.ToInt64(row[pinfo.Name]), null);
  631. // //else if (pinfo.PropertyType.ToString().ToLower().Contains("system.int32"))
  632. // // pinfo.SetValue(objj, Convert.ToInt32(row[pinfo.Name]), null);
  633. // //else
  634. // // pinfo.SetValue(objj, row[pinfo.Name], null);
  635. // #endregion
  636. // pinfo.SetValue(objj, Convert.ChangeType(row[pinfo.Name], pinfo.PropertyType.GetType()), null);
  637. // }
  638. // else
  639. // pinfo.SetValue(objj, null, null);
  640. // }
  641. // catch (Exception ex)
  642. // {
  643. // pinfo.SetValue(objj, null, null);
  644. //
  645. // }
  646. // }
  647. // if (pinfo.Name.Contains("PersistType"))
  648. // pinfo.SetValue(objj, EntityPersistType.Update, null);
  649. // if (pinfo.Name.Contains("Values"))
  650. // pinfo.SetValue(objj, vl, null);
  651. // }
  652. // return objj;
  653. //}
  654. ///// <summary>
  655. ///// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
  656. ///// </summary>
  657. ///// <typeparam name="T"></typeparam>
  658. ///// <param name="dt"></param>
  659. ///// <returns></returns>
  660. //public static T DataReader2Mod<T>(IDataReader dr)
  661. //{
  662. // T objj = (T)Activator.CreateInstance(typeof(T));
  663. // if (dr == null) return objj;
  664. // PropertyInfo[] propertys = objj.GetType().GetProperties();
  665. // foreach (PropertyInfo pi in propertys)
  666. // {
  667. // //DataTable MyDataTable = dr.GetSchemaTable();
  668. // //foreach (DataRow row in MyDataTable.Rows)
  669. // //{
  670. // // foreach (DataColumn col in MyDataTable.Columns)
  671. // // {
  672. // #region 属性与字段名称一致的进行赋值
  673. // // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
  674. // // {
  675. // // try
  676. // // {
  677. // // if (!Convert.IsDBNull(dr[row[0].ToString()]))
  678. // // {
  679. // // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
  680. // // {
  681. // // pi.SetValue(obj, Convert.ToInt64(dr[pi.Name]), null);
  682. // // }
  683. // // if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
  684. // // {
  685. // // pi.SetValue(obj, dr[pi.Name].ToInt32(), null);
  686. // // }
  687. // // else
  688. // // {
  689. // // pi.SetValue(obj, row[pi.Name], null);
  690. // // }
  691. // // }
  692. // // else
  693. // // pi.SetValue(obj, null, null);//为空,但不为Null
  694. // // }
  695. // // catch (Exception ex)
  696. // // {
  697. // // pi.SetValue(obj, null, null);//为空,但不为Null
  698. // //
  699. // // }
  700. // // }
  701. // #endregion
  702. // // }
  703. // //}
  704. // for (int k = 0; k < dr.FieldCount; k++)
  705. // {
  706. // if (!DBNull.Value.Equals(dr.GetValue(k)))
  707. // {
  708. // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
  709. // pi.SetValue(objj, Convert.ToInt64(dr.GetValue(k)), null);
  710. // else if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
  711. // pi.SetValue(objj, dr.GetValue(k).ToInt32(), null);
  712. // else
  713. // pi.SetValue(objj, dr.GetValue(k), null);
  714. // }
  715. // }
  716. // if (pi.Name.Contains("PersistType"))
  717. // {
  718. // pi.SetValue(objj, EntityPersistType.Update, null);
  719. // }
  720. // }
  721. // return objj;
  722. //}
  723. ///// <summary>
  724. ///// 这样也可以不过entity每次的值还在,缺点就是无法清除原先的值
  725. ///// </summary>
  726. ///// <param name="dr"></param>
  727. ///// <param name="md"></param>
  728. ///// <param name="enty"></param>
  729. ///// <returns></returns>
  730. //public static object DataReader2Entity(IDataReader dr, object enty)
  731. //{
  732. // object objj = Activator.CreateInstance(enty.GetType());
  733. // if (dr == null) return objj;
  734. // PropertyInfo[] propertys = enty.GetType().GetProperties();
  735. // foreach (PropertyInfo pi in propertys)
  736. // {
  737. // DataTable MyDataTable = dr.GetSchemaTable();
  738. // foreach (DataRow row in MyDataTable.Rows)
  739. // {
  740. // foreach (DataColumn col in MyDataTable.Columns)
  741. // {
  742. // #region 属性与字段名称一致的进行赋值
  743. // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
  744. // {
  745. // try
  746. // {
  747. // if (!Convert.IsDBNull(dr[row[0].ToString()]))
  748. // {
  749. // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
  750. // pi.SetValue(objj, Convert.ToInt64(dr[pi.Name]), null);
  751. // else if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
  752. // pi.SetValue(objj, dr[pi.Name].ToInt32(), null);
  753. // else
  754. // pi.SetValue(objj, row[pi.Name], null);
  755. // }
  756. // else
  757. // pi.SetValue(objj, null, null);//为空,但不为Null
  758. // }
  759. // catch (Exception ex)
  760. // {
  761. // pi.SetValue(objj, null, null);//为空,但不为Null
  762. //
  763. // }
  764. // }
  765. // #endregion
  766. // }
  767. // if (pi.Name.Contains("PersistType"))
  768. // {
  769. // pi.SetValue(objj, EntityPersistType.Update, null);
  770. // }
  771. // }
  772. // }
  773. // return objj;
  774. //}
  775. ///// <summary>
  776. ///// 将DataTable转换为list(用的FOR赋值,效果一样,这种比较复杂)
  777. ///// </summary>
  778. ///// <typeparam name="T"></typeparam>
  779. ///// <param name="dt"></param>
  780. ///// <returns></returns>
  781. //public static List<T> DataTable2List<T>(DataTable dt)
  782. //{
  783. // List<T> result = new List<T>(); string colname = "";
  784. // MetaData md = MetaDataManager.GetMetaData(typeof(T));
  785. // if (dt == null) return result;
  786. // for (int j = 0; j < dt.Rows.Count; j++)
  787. // {
  788. // T objj = (T)Activator.CreateInstance(typeof(T));
  789. // PropertyInfo[] propertys = objj.GetType().GetProperties();
  790. // foreach (PropertyInfo pi in propertys)
  791. // {
  792. // colname = "";
  793. // for (int i = 0; i < dt.Columns.Count; i++)
  794. // {
  795. // if (pi.Name.ToLower().Equals(dt.Columns[i].ColumnName.ToLower()))
  796. // {
  797. // colname = pi.Name; break;
  798. // }
  799. // }
  800. // if (!string.IsNullOrEmpty(colname))
  801. // {
  802. // #region 属性与字段名称一致的进行赋值
  803. // //if (dt.Rows[j][colname] != DBNull.Value && dt.Rows[j][colname] != null && !object.Equals(dt.Rows[j][colname], null))
  804. // if (!Convert.IsDBNull(dt.Rows[j][colname]))
  805. // {
  806. // try
  807. // {
  808. // pi.SetValue(objj, dt.Rows[j][md.FieldMeteDatas[colname].ColumnName], null);
  809. // }
  810. // catch (Exception ex)
  811. // {
  812. // pi.SetValue(objj, null, null);//为空,但不为Null
  813. //
  814. // }
  815. // }
  816. // else
  817. // {
  818. // pi.SetValue(objj, null, null);//为空,但不为Null
  819. // }
  820. // #endregion
  821. // }
  822. // if (pi.Name == "PersistType")
  823. // {
  824. // pi.SetValue(objj, EntityPersistType.Update, null);
  825. // }
  826. // }
  827. // result.Add(objj);
  828. // }
  829. // return result;
  830. //}
  831. /// <summary>
  832. /// 暂时不用
  833. /// </summary>
  834. /// <typeparam name="T"></typeparam>
  835. /// <param name="dr"></param>
  836. /// <returns></returns>
  837. //public static object DataTable2List<T>(IDataReader dr)
  838. //{
  839. // T obj = (T)Activator.CreateInstance(typeof(T));
  840. // MetaData md = MetaDataManager.GetMetaData(typeof(T));
  841. // if (dr == null) return obj;
  842. // PropertyInfo[] propertys = obj.GetType().GetProperties();
  843. // foreach (PropertyInfo pi in propertys)
  844. // {
  845. // DataTable MyDataTable = dr.GetSchemaTable();
  846. // foreach (DataRow row in MyDataTable.Rows)
  847. // {
  848. // foreach (DataColumn col in MyDataTable.Columns)
  849. // {
  850. // #region 属性与字段名称一致的进行赋值
  851. // if (pi.Name.ToLower().Equals(row[0].ToString().ToLower()))
  852. // {
  853. // //if (dr[row[0].ToString()] != DBNull.Value)
  854. // //if (dr[row[0].ToString()] != DBNull.Value && dr[row[0].ToString()] != null && !object.Equals(dr[row[0].ToString()], null))
  855. // if (!Convert.IsDBNull(dr[row[0].ToString()]))
  856. // {
  857. // if (pi.PropertyType.ToString().ToLower().Contains("system.int64"))
  858. // {
  859. // pi.SetValue(obj, Int64.Parse(dr[row[0].ToString()].ToString()), null);
  860. // }
  861. // if (pi.PropertyType.ToString().ToLower().Contains("system.int32"))
  862. // {
  863. // pi.SetValue(obj, Int32.Parse(dr[row[0].ToString()].ToString()), null);
  864. // }
  865. // else if (pi.PropertyType.ToString().ToLower().Contains("system.datetime"))
  866. // {
  867. // pi.SetValue(obj, Convert.ToDateTime(dr[row[0].ToString()].ToString()), null);
  868. // }
  869. // else if (pi.PropertyType.ToString().ToLower().Contains("system.boolean"))
  870. // {
  871. // pi.SetValue(obj, Convert.ToBoolean(dr[row[0].ToString()].ToString()), null);
  872. // }
  873. // else if (pi.PropertyType.ToString().ToLower().Contains("system.single"))
  874. // {
  875. // pi.SetValue(obj, Convert.ToSingle(dr[row[0].ToString()].ToString()), null);
  876. // }
  877. // else if (pi.PropertyType.ToString().ToLower().Contains("system.double"))
  878. // {
  879. // pi.SetValue(obj, Convert.ToDouble(dr[row[0].ToString()].ToString()), null);
  880. // }
  881. // else
  882. // {
  883. // pi.SetValue(obj, dr[md.FieldMeteDatas[pi.Name].ColumnName], null);
  884. // }
  885. // }
  886. // else
  887. // pi.SetValue(obj, null, null);//为空,但不为Null
  888. // }
  889. // #endregion
  890. // }
  891. // }
  892. // if (pi.Name == "PersistType")
  893. // {
  894. // pi.SetValue(obj, EntityPersistType.Update, null);
  895. // }
  896. // }
  897. // return obj;
  898. //}
  899. #endregion
  900. /// <summary>
  901. /// DataReader转Hashtable
  902. /// </summary>
  903. /// <param name="dr"></param>
  904. /// <returns></returns>
  905. public static Hashtable ReaderToHashtable(IDataReader dr)
  906. {
  907. Hashtable hashtable = new Hashtable();
  908. while (dr.Read())
  909. {
  910. for (int i = 0; i < dr.FieldCount; i++)
  911. {
  912. string str = dr.GetName(i).ToLower();
  913. hashtable[str] = dr[str];
  914. }
  915. }
  916. return hashtable;
  917. }
  918. /// <summary>
  919. /// DataReader转换成单个实体
  920. /// </summary>
  921. /// <typeparam name="T"></typeparam>
  922. /// <param name="dr"></param>
  923. /// <returns></returns>
  924. public static T ReaderToModel<T>(IDataReader dr)
  925. {
  926. T local = Activator.CreateInstance<T>();
  927. while (dr.Read())
  928. {
  929. foreach (PropertyInfo info in local.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
  930. {
  931. if (!IsNullOrDBNull(dr[info.Name]))
  932. {
  933. info.SetValue(local, HackType(dr[info.Name], info.PropertyType), null);
  934. }
  935. }
  936. }
  937. return local;
  938. }
  939. /// <summary>
  940. /// 判断是否为空
  941. /// </summary>
  942. /// <param name="obj"></param>
  943. /// <returns></returns>
  944. public static bool IsNullOrDBNull(object obj)
  945. {
  946. return ((obj is DBNull) || string.IsNullOrEmpty(obj.ToString()));
  947. }
  948. /// <summary>
  949. ///
  950. /// </summary>
  951. /// <param name="value"></param>
  952. /// <param name="conversionType"></param>
  953. /// <returns></returns>
  954. public static object HackType(object value, Type conversionType)
  955. {
  956. if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  957. {
  958. if (value == null)
  959. {
  960. return null;
  961. }
  962. NullableConverter converter = new NullableConverter(conversionType);
  963. conversionType = converter.UnderlyingType;
  964. }
  965. return Convert.ChangeType(value, conversionType);
  966. }
  967. /// <summary>
  968. /// 返回实体类的泛型列表
  969. /// </summary>
  970. /// <typeparam name="T">实体</typeparam>
  971. /// <param name="SqlTxt">SQL语句</param>
  972. /// <param name="paras">参数</param>
  973. /// <returns></returns>
  974. public static List<T> DrToEnList<T>(IDataReader rdr) where T : new()
  975. {
  976. try
  977. {
  978. List<T> ts = new List<T>();
  979. T t = new T();
  980. Type type = t.GetType();
  981. PropertyInfo[] pInfos = type.GetProperties();
  982. while (rdr.Read())
  983. {
  984. T mod = new T();
  985. for (int i = 0; i < rdr.FieldCount; i++)
  986. {
  987. string paraName = rdr.GetName(i);
  988. foreach (PropertyInfo pInfo in pInfos)
  989. {
  990. if (string.Compare(pInfo.Name, paraName, true) == 0)
  991. {
  992. pInfo.SetValue(mod, DBNull.Value == rdr[i] ? null : rdr[i], null);
  993. break;
  994. }
  995. }
  996. }
  997. ts.Add(mod);
  998. }
  999. return ts;
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. return null;
  1004. }
  1005. }
  1006. }
  1007. }