DataTableExtensions.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. using EasyDevCore.Common;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Data.Common;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace EasyDevCore.Database.EntityTable
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. public static class DataTableExtensions
  17. {
  18. /// <summary>
  19. /// Loads the asynchronous.
  20. /// </summary>
  21. /// <param name="source">The source.</param>
  22. /// <param name="reader">The reader.</param>
  23. /// <param name="cancellationToken">The cancellation token.</param>
  24. public static async Task LoadAsync(this DataTable source, DbDataReader reader, CancellationToken cancellationToken = default)
  25. {
  26. if (reader.IsClosed) return;
  27. int totalRows = source.Rows.Count;
  28. List<Tuple<int, int>> mapRcTcColumns = null;
  29. bool isFirst = true;
  30. while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
  31. {
  32. if (isFirst)
  33. {
  34. Dictionary<string, int> readerColumns = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);
  35. for (int i = 0; i < reader.FieldCount; i++)
  36. {
  37. readerColumns[reader.GetName(i)] = i;
  38. }
  39. if (source.Columns.Count == 0)
  40. {
  41. for (int col = 0; col < reader.FieldCount; col++)
  42. {
  43. source.Columns.Add(reader.GetName(col), reader.GetFieldType(col));
  44. }
  45. }
  46. mapRcTcColumns = (from rc in readerColumns
  47. join tc in source.Columns.Cast<DataColumn>() on rc.Key equals tc.ColumnName
  48. select new Tuple<int, int>(rc.Value, tc.Ordinal)).ToList();
  49. isFirst = false;
  50. }
  51. var newRow = source.NewRow();
  52. for (int i = 0; i < mapRcTcColumns.Count; i++)
  53. {
  54. newRow[mapRcTcColumns[i].Item2] = reader.GetValue(mapRcTcColumns[i].Item1) ?? DBNull.Value;
  55. }
  56. source.Rows.Add(newRow);
  57. }
  58. bool hasNextResult = await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
  59. if (!hasNextResult) await reader.CloseAsync().ConfigureAwait(false);
  60. }
  61. /// <summary>
  62. /// Firsts the or add.
  63. /// </summary>
  64. /// <typeparam name="TSource">The type of the source.</typeparam>
  65. /// <param name="source">The source.</param>
  66. /// <returns></returns>
  67. public static TSource FirstOrAdd<TSource>(this DataTable source) where TSource : DataRow
  68. {
  69. if (source.Rows.Count == 0)
  70. {
  71. return (TSource)(source as DataTable).DefaultView.AddNew().Row;
  72. }
  73. else
  74. {
  75. return (TSource)(source as DataTable).DefaultView[0].Row;
  76. }
  77. }
  78. /// <summary>
  79. /// Ases the enumberable.
  80. /// </summary>
  81. /// <param name="source">The source.</param>
  82. /// <returns></returns>
  83. public static IEnumerable<DataRow> AsEnumberable(this DataTable source)
  84. {
  85. System.Collections.IEnumerator iterator = source.AsEnumberable().GetEnumerator();
  86. while (iterator.MoveNext())
  87. {
  88. yield return (DataRow)iterator.Current;
  89. }
  90. }
  91. /// <summary>
  92. /// Adds the new row.
  93. /// </summary>
  94. /// <param name="source">The source.</param>
  95. /// <returns></returns>
  96. public static DataRow AddNewRow(this DataTable source)
  97. {
  98. var newRow = source.NewRow();
  99. source.Rows.Add(newRow);
  100. return newRow;
  101. }
  102. /// <summary>
  103. /// Finds the DataRow.
  104. /// </summary>
  105. /// <param name="source">The source.</param>
  106. /// <param name="values">The values.</param>
  107. /// <returns></returns>
  108. public static DataRow FindDataRow(this DataTable source, params object[] values)
  109. {
  110. var argValues = ArgumentHelper.GetArgValues(values);
  111. DataView view = new DataView(source as DataTable, string.Empty, string.Join(",", argValues.Keys), DataViewRowState.CurrentRows);
  112. int rowIndex = view.Find(argValues.Values.ToArray());
  113. return rowIndex == -1 ? null : view[rowIndex].Row;
  114. }
  115. /// <summary>
  116. /// Gets the index of the specified DataRow object.
  117. /// </summary>
  118. /// <param name="source">The source.</param>
  119. /// <param name="DataRow">The DataRow.</param>
  120. /// <returns></returns>
  121. public static int IndexOf(this DataTable source, DataRow DataRow)
  122. {
  123. return source.IndexOf(DataRow);
  124. }
  125. /// <summary>
  126. /// Gets the matched columns list.
  127. /// </summary>
  128. /// <param name="source">The source.</param>
  129. /// <param name="dest">The dest.</param>
  130. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  131. /// <param name="exceptColumnNames">The except column names.</param>
  132. /// <returns></returns>
  133. internal static IDictionary<string, string> GetMatchedColumnsList(this DataTable source, DataTable dest, string columnNames = "", string exceptColumnNames = "")
  134. {
  135. bool hasMapping = columnNames.Contains("=");
  136. IEnumerable<string> colNames = columnNames.SplitCommaString(trimSpace: true);
  137. if (columnNames.Contains("*") || string.IsNullOrWhiteSpace(columnNames))
  138. {
  139. colNames = from s in source.Columns.OfType<DataColumn>()
  140. join d in dest.Columns.OfType<DataColumn>() on s.ColumnName equals d.ColumnName
  141. select s.ColumnName;
  142. }
  143. HashSet<string> exceptColNames = new HashSet<string>(exceptColumnNames.SplitCommaString(trimSpace: true));
  144. Dictionary<string, string> mapColumns = colNames.Where(c => !exceptColNames.Contains(c))
  145. .Select((s) =>
  146. {
  147. if (hasMapping && s.Contains("="))
  148. {
  149. var names = s.SplitString("=", trimSpace: true);
  150. return new { Key = names[0], Value = names[1] };
  151. }
  152. return new { Key = s, Value = s };
  153. }).ToDictionary(k => k.Key, v => v.Value);
  154. return mapColumns;
  155. }
  156. /// <summary>
  157. /// Gets the matched properties list.
  158. /// </summary>
  159. /// <typeparam name="T"></typeparam>
  160. /// <param name="source">The source.</param>
  161. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  162. /// <param name="exceptColumnNames">The except column names.</param>
  163. /// <param name="ignorePrefix">The ignore prefix.</param>
  164. /// <returns>IDictionary&lt;System.String, PropertyDescriptor&gt;.</returns>
  165. internal static IDictionary<string, PropertyDescriptor> GetMatchedPropertiesList<T>(this DataTable source, string columnNames = "", string exceptColumnNames = "", string ignorePrefix = "")
  166. {
  167. if (source == null)
  168. {
  169. return new Dictionary<string, PropertyDescriptor>();
  170. }
  171. Type DataRowType = typeof(T);
  172. bool mapAllColumns = columnNames.Contains("*") || string.IsNullOrWhiteSpace(columnNames);
  173. bool hasIgnorePrefix = !string.IsNullOrWhiteSpace(ignorePrefix);
  174. string[] ignorePrefixes = ignorePrefix.SplitByCommaOrSemiColon();
  175. bool hasMapping = columnNames.Contains("=");
  176. bool hasExceptColumn = !string.IsNullOrWhiteSpace(exceptColumnNames);
  177. string[] exceptColNames = exceptColumnNames.SplitCommaString(trimSpace: true);
  178. Dictionary<string, PropertyDescriptor> allProperties = TypeDescriptor.GetProperties(DataRowType).Cast<PropertyDescriptor>().ToDictionary(p =>
  179. {
  180. if (hasIgnorePrefix)
  181. {
  182. if (ignorePrefixes.Length > 1)
  183. {
  184. foreach (var prefix in ignorePrefixes)
  185. {
  186. if (prefix.StartsWith(prefix))
  187. {
  188. return p.Name.Substring(prefix.Length);
  189. }
  190. }
  191. }
  192. else if (p.Name.StartsWith(ignorePrefix))
  193. {
  194. return p.Name.Substring(ignorePrefix.Length);
  195. }
  196. }
  197. return p.Name;
  198. });
  199. Dictionary<string, string> colNames = columnNames.SplitCommaString(trimSpace: true)
  200. .Where(c => !mapAllColumns || !c.Contains("*"))
  201. .Select((s) =>
  202. {
  203. if (hasMapping && s.Contains("="))
  204. {
  205. var names = s.SplitString("=", trimSpace: true);
  206. return new { Key = names[0], Value = names[1] };
  207. }
  208. return new { Key = s, Value = s };
  209. }).ToDictionary(k => k.Key, v => v.Value);
  210. IDictionary<string, PropertyDescriptor> mapProperties = source.Columns.Cast<DataColumn>()
  211. .Select(c => new { c.ColumnName, PropertyName = colNames.ContainsKey(c.ColumnName) ? colNames[c.ColumnName] : c.ColumnName })
  212. .Where(c => (mapAllColumns || colNames.ContainsKey(c.ColumnName))
  213. && allProperties.ContainsKey(c.PropertyName)
  214. && (!hasExceptColumn || Array.IndexOf(exceptColNames, c.ColumnName) == -1)
  215. )
  216. .ToDictionary(c => c.ColumnName, c => allProperties[c.PropertyName]);
  217. return mapProperties;
  218. }
  219. /// <summary>
  220. /// Imports from model list.
  221. /// </summary>
  222. /// <typeparam name="T"></typeparam>
  223. /// <param name="source">The source.</param>
  224. /// <param name="list">The list.</param>
  225. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  226. /// <param name="exceptColumnNames">The except column names.</param>
  227. /// <param name="ignorePrefix">The ignore prefix.</param>
  228. public static void ImportFromModel<T>(this DataTable source, IList<T> list, string columnNames = "", string exceptColumnNames = "", string ignorePrefix = "")
  229. {
  230. Type DataRowType = typeof(T);
  231. IDictionary<string, PropertyDescriptor> updateProperties = source.GetMatchedPropertiesList<T>(columnNames, exceptColumnNames, ignorePrefix);
  232. foreach (T item in list)
  233. {
  234. var newRow = source.NewRow();
  235. newRow.UpdateFromModel(item, updateProperties);
  236. source.Rows.Add(newRow);
  237. }
  238. }
  239. /// <summary>
  240. /// Convert to Model List.
  241. /// </summary>
  242. /// <typeparam name="T"></typeparam>
  243. /// <param name="source">The source.</param>
  244. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  245. /// <param name="exceptColumnNames">The except column names.</param>
  246. /// <param name="modelStatusField">The model status field has receive status of source (field type must be DataRowState).</param>
  247. /// <param name="ignorePrefix">The ignore prefix.</param>
  248. /// <param name="method">The method.</param>
  249. /// <returns>IList&lt;T&gt;.</returns>
  250. public static IList<T> ConvertToModel<T>(this DataTable source, string columnNames = "", string exceptColumnNames = "", string modelStatusField = "", string ignorePrefix = "", Action<T> method = null)
  251. {
  252. Type DataRowType = typeof(T);
  253. IDictionary<string, PropertyDescriptor> updateProperties = source.GetMatchedPropertiesList<T>(columnNames, exceptColumnNames, ignorePrefix);
  254. IList<T> list = new List<T>();
  255. if (source != null)
  256. {
  257. foreach (DataRow DataRow in source.Rows)
  258. {
  259. list.Add(DataRow.ConvertToModel(updateProperties, modelStatusField, method: method));
  260. }
  261. }
  262. return list;
  263. }
  264. /// <summary>
  265. /// Updates from DataRow.
  266. /// </summary>
  267. /// <param name="source">The source.</param>
  268. /// <param name="value">The value.</param>
  269. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  270. /// <param name="exceptColumnNames">The except column names.</param>
  271. /// <param name="keyFields">The key fields. (if not include key fields, auto use keys value to fields)</param>
  272. /// <returns></returns>
  273. public static bool UpdateFrom(this DataTable source, DataRow value, string columnNames = "", string exceptColumnNames = "", string keyFields = "")
  274. {
  275. string keysColumns = string.Empty;
  276. List<string> columnList = new List<string>();
  277. List<object> keysValues = new List<object>();
  278. if (string.IsNullOrWhiteSpace(keyFields))
  279. {
  280. if (source.PrimaryKey?.Length > 0)
  281. {
  282. foreach (var key in source.PrimaryKey)
  283. {
  284. columnList.Add(key.ColumnName);
  285. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + key.ColumnName;
  286. }
  287. }
  288. else
  289. {
  290. foreach (DataColumn col in source.Columns)
  291. {
  292. if (col.AutoIncrement)
  293. {
  294. columnList.Add(col.ColumnName);
  295. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + col.ColumnName;
  296. }
  297. }
  298. }
  299. }
  300. else
  301. {
  302. keysColumns = keyFields;
  303. columnList.AddRange(keysColumns.SplitCommaString(trimSpace: true));
  304. }
  305. foreach (string columnName in columnList)
  306. {
  307. keysValues.Add(value.GetValue(columnName));
  308. }
  309. DataRow row = source.FindDataRow(keysColumns, keysValues.ToArray());
  310. if (row != null)
  311. {
  312. row.UpdateFrom(value, columnNames, exceptColumnNames);
  313. return true;
  314. }
  315. return false;
  316. }
  317. /// <summary>
  318. /// Synches from table.
  319. /// </summary>
  320. /// <param name="source">The source.</param>
  321. /// <param name="values">The values.</param>
  322. /// <param name="columnUpdateNames">The column update names.</param>
  323. /// <param name="columnAddNewNames">The column add new names.</param>
  324. /// <param name="exceptUpdateColumnNames">The except update column names.</param>
  325. /// <param name="exceptAddNewColumnNames">The except add new column names.</param>
  326. /// <param name="keyFields">The key fields.</param>
  327. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  328. public static void SynchFromTable(this DataTable source, DataTable values, string columnUpdateNames = "", string columnAddNewNames = "", string exceptUpdateColumnNames = "", string exceptAddNewColumnNames = "", string keyFields = "")
  329. {
  330. string keysColumns = string.Empty;
  331. List<string> columnList = new List<string>();
  332. List<object> keysValues = new List<object>();
  333. if (string.IsNullOrWhiteSpace(keyFields))
  334. {
  335. if (source.PrimaryKey?.Length > 0)
  336. {
  337. foreach (var key in source.PrimaryKey)
  338. {
  339. columnList.Add(key.ColumnName);
  340. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + key.ColumnName;
  341. }
  342. }
  343. else
  344. {
  345. foreach (DataColumn col in source.Columns)
  346. {
  347. if (col.AutoIncrement)
  348. {
  349. columnList.Add(col.ColumnName);
  350. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + col.ColumnName;
  351. }
  352. }
  353. }
  354. }
  355. else
  356. {
  357. keysColumns = keyFields;
  358. columnList.AddRange(keysColumns.SplitCommaString(trimSpace: true));
  359. }
  360. IDictionary<string, string> updateColumns = values.GetMatchedColumnsList(source, columnUpdateNames, exceptUpdateColumnNames);
  361. IDictionary<string, string> addNewColumns = values.GetMatchedColumnsList(source, columnAddNewNames, exceptAddNewColumnNames);
  362. DataView view = new DataView(source, string.Empty, keysColumns, DataViewRowState.CurrentRows);
  363. List<DataRow> listSynchItems = new List<DataRow>();
  364. foreach (DataRow item in values.Rows)
  365. {
  366. keysValues.Clear();
  367. foreach (string columnName in columnList)
  368. {
  369. keysValues.Add(item.GetValue(columnName));
  370. }
  371. var rows = view.FindRows(keysValues.ToArray());
  372. DataRow DataRow = rows != null && rows.Length > 0 ? rows[0].Row : null;
  373. if (DataRow != null)
  374. {
  375. foreach (var map in updateColumns)
  376. {
  377. DataRow.SetValue(map.Key, item[map.Value]);
  378. }
  379. listSynchItems.Add(DataRow);
  380. }
  381. else
  382. {
  383. DataRow = source.AddNewRow();
  384. foreach (var map in addNewColumns)
  385. {
  386. DataRow.SetValue(map.Key, item[map.Value]);
  387. }
  388. listSynchItems.Add(DataRow);
  389. }
  390. }
  391. if (listSynchItems.Count != view.Count)
  392. {
  393. foreach (var deletedItem in source.AsEnumerable().Where(r => listSynchItems.IndexOf(r) < 0).ToArray())
  394. {
  395. deletedItem.Delete();
  396. }
  397. }
  398. }
  399. /// <summary>
  400. /// Synches from model.
  401. /// </summary>
  402. /// <typeparam name="T"></typeparam>
  403. /// <param name="source">The source.</param>
  404. /// <param name="values">The values.</param>
  405. /// <param name="columnUpdateNames">The column update names.</param>
  406. /// <param name="columnAddNewNames">The column add new names.</param>
  407. /// <param name="exceptUpdateColumnNames">The except update column names.</param>
  408. /// <param name="exceptAddNewColumnNames">The except add new column names.</param>
  409. /// <param name="keyFields">The key fields.</param>
  410. /// <param name="ignorePrefix">The ignore prefix.</param>
  411. public static void SynchFromModel<T>(this DataTable source, IEnumerable<T> values, string columnUpdateNames = "", string columnAddNewNames = "", string exceptUpdateColumnNames = "", string exceptAddNewColumnNames = "", string keyFields = "", string ignorePrefix = "")
  412. {
  413. string keysColumns = string.Empty;
  414. List<string> columnList = new List<string>();
  415. List<object> keysValues = new List<object>();
  416. if (string.IsNullOrWhiteSpace(keyFields))
  417. {
  418. if (source.PrimaryKey?.Length > 0)
  419. {
  420. foreach (var key in source.PrimaryKey)
  421. {
  422. columnList.Add(key.ColumnName);
  423. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + key.ColumnName;
  424. }
  425. }
  426. else
  427. {
  428. foreach (DataColumn col in source.Columns)
  429. {
  430. if (col.AutoIncrement)
  431. {
  432. columnList.Add(col.ColumnName);
  433. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + col.ColumnName;
  434. }
  435. }
  436. }
  437. }
  438. else
  439. {
  440. keysColumns = keyFields;
  441. columnList.AddRange(keysColumns.SplitCommaString(trimSpace: true));
  442. }
  443. IDictionary<string, PropertyDescriptor> updateProperties = source.GetMatchedPropertiesList<T>(columnUpdateNames, exceptUpdateColumnNames, ignorePrefix);
  444. IDictionary<string, PropertyDescriptor> addNewProperties = source.GetMatchedPropertiesList<T>(columnAddNewNames, exceptAddNewColumnNames, ignorePrefix);
  445. DataView view = new DataView(source, string.Empty, keysColumns, DataViewRowState.CurrentRows);
  446. List<DataRow> listSynchItems = new List<DataRow>();
  447. foreach (T item in values)
  448. {
  449. keysValues.Clear();
  450. foreach (string columnName in columnList)
  451. {
  452. keysValues.Add(item.GetPropertyValue(columnName));
  453. }
  454. var rows = view.FindRows(keysValues.ToArray());
  455. DataRow DataRow = rows != null && rows.Length > 0 ? rows[0].Row : null;
  456. if (DataRow != null)
  457. {
  458. listSynchItems.Add(DataRow);
  459. DataRow.UpdateFromModel(item, updateProperties);
  460. }
  461. else
  462. {
  463. DataRow = source.AddNewRow();
  464. DataRow.UpdateFromModel(item, addNewProperties);
  465. listSynchItems.Add(DataRow);
  466. }
  467. }
  468. if (listSynchItems.Count != view.Count)
  469. {
  470. foreach (var deletedItem in source.AsEnumerable().Where(r => listSynchItems.IndexOf(r) < 0).ToArray())
  471. {
  472. deletedItem.Delete();
  473. }
  474. }
  475. }
  476. /// <summary>
  477. /// Updates from model.
  478. /// </summary>
  479. /// <typeparam name="T"></typeparam>
  480. /// <param name="source">The source.</param>
  481. /// <param name="value">The value.</param>
  482. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  483. /// <param name="exceptColumnNames">The except column names.</param>
  484. /// <param name="keyFields">The key fields.</param>
  485. /// <param name="ignorePrefix">The ignore prefix.</param>
  486. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  487. public static bool UpdateFromModel<T>(this DataTable source, T value, string columnNames = "", string exceptColumnNames = "", string keyFields = "", string ignorePrefix = "")
  488. {
  489. string keysColumns = string.Empty;
  490. List<string> columnList = new List<string>();
  491. List<object> keysValues = new List<object>();
  492. if (string.IsNullOrWhiteSpace(keyFields))
  493. {
  494. if (source.PrimaryKey?.Length > 0)
  495. {
  496. foreach (var key in source.PrimaryKey)
  497. {
  498. columnList.Add(key.ColumnName);
  499. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + key.ColumnName;
  500. }
  501. }
  502. else
  503. {
  504. foreach (DataColumn col in source.Columns)
  505. {
  506. if (col.AutoIncrement)
  507. {
  508. columnList.Add(col.ColumnName);
  509. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + col.ColumnName;
  510. }
  511. }
  512. }
  513. }
  514. else
  515. {
  516. keysColumns = keyFields;
  517. columnList.AddRange(keysColumns.SplitCommaString(trimSpace: true));
  518. }
  519. foreach (string columnName in columnList)
  520. {
  521. keysValues.Add(value.GetPropertyValue(columnName));
  522. }
  523. IDictionary<string, PropertyDescriptor> updateProperties = source.GetMatchedPropertiesList<T>(columnNames, exceptColumnNames, ignorePrefix);
  524. DataRow row = source.FindDataRow(keysColumns, keysValues.ToArray());
  525. if (row != null)
  526. {
  527. row.UpdateFromModel(value, updateProperties);
  528. return true;
  529. }
  530. return false;
  531. }
  532. /// <summary>
  533. /// Updates from model.
  534. /// </summary>
  535. /// <typeparam name="T"></typeparam>
  536. /// <param name="source">The source.</param>
  537. /// <param name="values">The values.</param>
  538. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  539. /// <param name="exceptColumnNames">The except column names.</param>
  540. /// <param name="keyFields">The key fields.</param>
  541. /// <param name="ignorePrefix">The ignore prefix.</param>
  542. public static void UpdateFromModel<T>(this DataTable source, IEnumerable<T> values, string columnNames = "", string exceptColumnNames = "", string keyFields = "", string ignorePrefix = "")
  543. {
  544. string keysColumns = string.Empty;
  545. List<string> columnList = new List<string>();
  546. List<object> keysValues = new List<object>();
  547. if (string.IsNullOrWhiteSpace(keyFields))
  548. {
  549. if (source.PrimaryKey?.Length > 0)
  550. {
  551. foreach (var key in source.PrimaryKey)
  552. {
  553. columnList.Add(key.ColumnName);
  554. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + key.ColumnName;
  555. }
  556. }
  557. else
  558. {
  559. foreach (DataColumn col in source.Columns)
  560. {
  561. if (col.AutoIncrement)
  562. {
  563. columnList.Add(col.ColumnName);
  564. keysColumns += (string.IsNullOrWhiteSpace(keysColumns) ? string.Empty : ",") + col.ColumnName;
  565. }
  566. }
  567. }
  568. }
  569. else
  570. {
  571. keysColumns = keyFields;
  572. columnList.AddRange(keysColumns.SplitCommaString(trimSpace: true));
  573. }
  574. IDictionary<string, PropertyDescriptor> updateProperties = source.GetMatchedPropertiesList<T>(columnNames, exceptColumnNames, ignorePrefix);
  575. DataView view = new DataView(source, string.Empty, keysColumns, DataViewRowState.CurrentRows);
  576. foreach (T item in values)
  577. {
  578. keysValues.Clear();
  579. foreach (string columnName in columnList)
  580. {
  581. keysValues.Add(item.GetPropertyValue(columnName));
  582. }
  583. DataRow DataRow = view.FindRows(keysValues.ToArray())[0].Row;
  584. DataRow.UpdateFromModel(item, updateProperties);
  585. }
  586. }
  587. ///// <summary>
  588. ///// Import Raw XML to DataTable
  589. ///// </summary>
  590. ///// <param name="source">The source.</param>
  591. ///// <param name="xml">The XML.</param>
  592. //public static void ImportFromRawXML(this DataTable source, string xml)
  593. //{
  594. // ImportFromXML(source, null, xml);
  595. //}
  596. ///// <summary>
  597. ///// Import XML to DataTable
  598. ///// </summary>
  599. ///// <param name="source">The source.</param>
  600. ///// <param name="rootName">Name of the root.</param>
  601. ///// <param name="xml">The XML.</param>
  602. //public static void ImportFromRawXML(this DataTable source, string rootName, string xml)
  603. //{
  604. // DataTable entities = DataTable.CreateFromRawXML(xml, rootName);
  605. // foreach (DataRow DataRow in entities) source.ImportFrom(entities);
  606. //}
  607. ///// <summary>
  608. ///// Import XML to DataTable
  609. ///// </summary>
  610. ///// <param name="source">The source.</param>
  611. ///// <param name="xml">The XML.</param>
  612. //public static void ImportFromXML(this DataTable source, string xml)
  613. //{
  614. // ImportFromXML(source, null, xml);
  615. //}
  616. ///// <summary>
  617. ///// Import XML to DataTable
  618. ///// </summary>
  619. ///// <param name="source">The source.</param>
  620. ///// <param name="rootName">Name of the root.</param>
  621. ///// <param name="xml">The XML.</param>
  622. //public static void ImportFromXML(this DataTable source, string rootName, string xml)
  623. //{
  624. // DataTable entities = DataTable.CreateFromXML(xml, rootName);
  625. // foreach (DataRow DataRow in entities) source.ImportFrom(entities);
  626. //}
  627. }
  628. }