You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1231 lines
52 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
2 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
3 years ago
2 years ago
3 years ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
2 years ago
3 years ago
4 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace Apewer.Source
  7. {
  8. /// <summary>ORM 帮助程序。</summary>
  9. public static class SourceUtility
  10. {
  11. #region ORM
  12. /// <summary>读取所有行,生成列表。</summary>
  13. public static T[] Fill<T>(this IQuery query) where T : class, new()
  14. {
  15. var objects = Fill(query, typeof(T));
  16. var array = CollectionUtility.As<object, T>(objects);
  17. return array;
  18. }
  19. /// <summary>读取所有行填充到 T,组成 T[]。</summary>
  20. /// <exception cref="ArgumentNullException"></exception>
  21. /// <exception cref="ArgumentException"></exception>
  22. public static object[] Fill(this IQuery query, Type model)
  23. {
  24. if (query == null) return new object[0];
  25. if (query.Table == null) return new object[0];
  26. if (model == null) return new object[0];
  27. return Fill(query.Table, model);
  28. }
  29. /// <summary>将 Query 的行,填充到模型实体。</summary>
  30. /// <remarks>填充失败时返回 NULL 值。</remarks>
  31. /// <exception cref="Exception"></exception>
  32. public static object FillRow(IQuery query, int rowIndex, Type model, TableStructure structure) => FillRow(query?.Table, rowIndex, model, structure);
  33. /// <summary>将 Query 的行,填充到模型实体。</summary>
  34. /// <remarks>填充失败时返回 NULL 值。</remarks>
  35. /// <exception cref="Exception"></exception>
  36. public static object FillRow(DataTable table, int rowIndex, Type model, TableStructure structure)
  37. {
  38. // 检查参数。
  39. if (table == null || model == null || structure == null) return null;
  40. if (rowIndex < 0 || rowIndex >= table.Rows.Count) return null;
  41. if (!RuntimeUtility.CanNew(model)) return null;
  42. // 变量别名。
  43. var ts = structure;
  44. var r = rowIndex;
  45. var columns = ts.Columns;
  46. // 检查模型的属性,按属性从表中取相应的列。
  47. var record = Activator.CreateInstance(model);
  48. var properties = model.GetProperties();
  49. foreach (var property in properties)
  50. {
  51. // 在表结构中检查,是否包含此属性,并获取 ColumnAttribute 中的 Field。
  52. var field = null as string;
  53. for (var j = 0; j < columns.Length; j++)
  54. {
  55. if (columns[j].PropertyName == property.Name)
  56. {
  57. field = columns[j].Field;
  58. break;
  59. }
  60. }
  61. if (field == null)
  62. {
  63. if (ts && ts.Table.AllProperties) continue;
  64. field = property.Name;
  65. }
  66. var value = table.Rows[r][field];
  67. if (value != null && value.Equals(DBNull.Value)) value = null;
  68. var setted = Set(record, property, value);
  69. }
  70. return record;
  71. }
  72. static bool Set(object record, PropertyInfo property, object value)
  73. {
  74. // 读取值。
  75. if (value == null) return false;
  76. if (value.Equals(DBNull.Value)) return false;
  77. // 必须有 setter 访问器。
  78. var setter = property.GetSetMethod();
  79. if (setter == null) return false;
  80. // 根据属性类型设置值。
  81. var pt = property.PropertyType;
  82. if (pt.Equals(typeof(object))) setter.Invoke(record, new object[] { value });
  83. else if (pt.Equals(typeof(byte[]))) setter.Invoke(record, new object[] { (byte[])value });
  84. else if (pt.Equals(typeof(string))) setter.Invoke(record, new object[] { value.ToString() });
  85. else if (pt.Equals(typeof(DateTime))) setter.Invoke(record, new object[] { value });
  86. else if (pt.Equals(typeof(bool))) setter.Invoke(record, new object[] { NumberUtility.Boolean(value) });
  87. else if (pt.Equals(typeof(byte))) setter.Invoke(record, new object[] { NumberUtility.Byte(value) });
  88. else if (pt.Equals(typeof(sbyte))) setter.Invoke(record, new object[] { NumberUtility.SByte(value) });
  89. else if (pt.Equals(typeof(short))) setter.Invoke(record, new object[] { NumberUtility.Int16(value) });
  90. else if (pt.Equals(typeof(ushort))) setter.Invoke(record, new object[] { NumberUtility.UInt16(value) });
  91. else if (pt.Equals(typeof(int))) setter.Invoke(record, new object[] { NumberUtility.Int32(value) });
  92. else if (pt.Equals(typeof(uint))) setter.Invoke(record, new object[] { NumberUtility.UInt32(value) });
  93. else if (pt.Equals(typeof(long))) setter.Invoke(record, new object[] { NumberUtility.Int64(value) });
  94. else if (pt.Equals(typeof(ulong))) setter.Invoke(record, new object[] { NumberUtility.UInt64(value) });
  95. else if (pt.Equals(typeof(float))) setter.Invoke(record, new object[] { NumberUtility.Single(value) });
  96. else if (pt.Equals(typeof(double))) setter.Invoke(record, new object[] { NumberUtility.Double(value) });
  97. else if (pt.Equals(typeof(decimal))) setter.Invoke(record, new object[] { NumberUtility.Decimal(value) });
  98. #if !NET20
  99. else if (pt.Equals(typeof(Nullable<DateTime>))) setter.Invoke(record, new object[] { new Nullable<DateTime>((DateTime)value) });
  100. else if (pt.Equals(typeof(Nullable<bool>))) setter.Invoke(record, new object[] { new Nullable<bool>(NumberUtility.Boolean(value)) });
  101. else if (pt.Equals(typeof(Nullable<byte>))) setter.Invoke(record, new object[] { new Nullable<byte>(NumberUtility.Byte(value)) });
  102. else if (pt.Equals(typeof(Nullable<sbyte>))) setter.Invoke(record, new object[] { new Nullable<sbyte>(NumberUtility.SByte(value)) });
  103. else if (pt.Equals(typeof(Nullable<short>))) setter.Invoke(record, new object[] { new Nullable<short>(NumberUtility.Int16(value)) });
  104. else if (pt.Equals(typeof(Nullable<ushort>))) setter.Invoke(record, new object[] { new Nullable<int>(NumberUtility.UInt16(value)) });
  105. else if (pt.Equals(typeof(Nullable<int>))) setter.Invoke(record, new object[] { new Nullable<int>(NumberUtility.Int32(value)) });
  106. else if (pt.Equals(typeof(Nullable<uint>))) setter.Invoke(record, new object[] { new Nullable<uint>(NumberUtility.UInt32(value)) });
  107. else if (pt.Equals(typeof(Nullable<long>))) setter.Invoke(record, new object[] { new Nullable<long>(NumberUtility.Int64(value)) });
  108. else if (pt.Equals(typeof(Nullable<ulong>))) setter.Invoke(record, new object[] { new Nullable<ulong>(NumberUtility.UInt64(value)) });
  109. else if (pt.Equals(typeof(Nullable<float>))) setter.Invoke(record, new object[] { new Nullable<float>(NumberUtility.Single(value)) });
  110. else if (pt.Equals(typeof(Nullable<double>))) setter.Invoke(record, new object[] { new Nullable<double>(NumberUtility.Double(value)) });
  111. else if (pt.Equals(typeof(Nullable<decimal>))) setter.Invoke(record, new object[] { new Nullable<decimal>(NumberUtility.Decimal(value)) });
  112. #endif
  113. else
  114. {
  115. try
  116. {
  117. setter.Invoke(record, new object[] { value });
  118. return true;
  119. }
  120. catch { }
  121. }
  122. return false;
  123. }
  124. /// <summary>解析 DataTable,填充没行到到指定的类型中,形成数组。</summary>
  125. /// <param name="table">将要读取的表。</param>
  126. /// <param name="compatible">当类型不同时,尝试转换以兼容。</param>
  127. /// <returns>由指定类型组成的数组。</returns>
  128. /// <exception cref="ArgumentNullException"></exception>
  129. /// <exception cref="ArgumentException"></exception>
  130. public static T[] Fill<T>(this DataTable table, bool compatible = true)
  131. {
  132. if (table == null) throw new ArgumentNullException(nameof(table), $"参数 {table} 无效。");
  133. var objects = Fill(table, typeof(T), compatible);
  134. var count = objects.Length;
  135. var array = new T[count];
  136. for (var i = 0; i < count; i++) array[i] = (T)objects[i];
  137. return array;
  138. }
  139. /// <summary>解析 DataTable,填充没行到到指定的类型中,形成数组。</summary>
  140. /// <param name="table">将要读取的表。</param>
  141. /// <param name="model">要填充的目标类型,必须是可实例化的引用类型。</param>
  142. /// <param name="compatible">当类型不同时,尝试转换以兼容。</param>
  143. /// <returns>由指定类型组成的数组。</returns>
  144. /// <exception cref="ArgumentNullException"></exception>
  145. /// <exception cref="ArgumentException"></exception>
  146. public static object[] Fill(this DataTable table, Type model, bool compatible = true)
  147. {
  148. if (table == null) throw new ArgumentNullException(nameof(table), $"参数 {table} 无效。");
  149. if (model == null) throw new ArgumentNullException(nameof(model), $"参数 {model} 无效。");
  150. // 检查模型是否允许填充。
  151. var ts = TableStructure.Parse(model, true, true);
  152. if (ts == null) throw new ArgumentException($"无法填充到类型 {model.FullName} 中。");
  153. // 检查行数。
  154. var rows = table.Rows;
  155. var rowsCount = rows.Count;
  156. if (rowsCount < 1) return new object[0];
  157. // 确定数组。
  158. var array = new object[rowsCount];
  159. for (var i = 0; i < rowsCount; i++) array[i] = Activator.CreateInstance(model, true);
  160. // 检查列数。
  161. var columns = table.Columns;
  162. var columnsCount = columns.Count;
  163. if (columnsCount < 1) return array;
  164. // 解析表头,仅保留有名称的列。
  165. var sc = 0;
  166. var sfs = new string[columnsCount];
  167. var sts = new Type[columnsCount];
  168. var sis = new int[columnsCount];
  169. for (var i = 0; i < columnsCount; i++)
  170. {
  171. var column = columns[i];
  172. var key = column.ColumnName.Lower();
  173. if (string.IsNullOrEmpty(key)) continue;
  174. if (sfs.Contains(key)) continue;
  175. sfs[sc] = key;
  176. sts[sc] = column.DataType;
  177. sis[sc] = i;
  178. sc++;
  179. }
  180. if (sc < 1) return array;
  181. // 解析模型列。
  182. var cas = ts.Fillable;
  183. var dc = 0;
  184. var dfs = new string[cas.Length];
  185. var dts = new ColumnAttribute[cas.Length];
  186. for (var i = 0; i < cas.Length; i++)
  187. {
  188. var ca = cas[i];
  189. var key = ca.Field.Lower();
  190. if (string.IsNullOrEmpty(key)) continue;
  191. if (dfs.Contains(key)) continue;
  192. dfs[dc] = key;
  193. dts[dc] = ca;
  194. dc++;
  195. }
  196. if (dc < 1) return array;
  197. // 遍历、填充。
  198. for (var r = 0; r < rowsCount; r++)
  199. {
  200. var record = array[r];
  201. // 遍历 table 的列。
  202. for (var s = 0; s < sc; s++)
  203. {
  204. var sf = sfs[s];
  205. // 遍历 model 的列。
  206. for (var d = 0; d < dc; d++)
  207. {
  208. var df = dfs[d];
  209. if (df != sf) continue;
  210. // 取值、填充。
  211. var value = rows[r][sis[s]];
  212. Fill(record, dts[d], sts[s], value, compatible);
  213. break;
  214. }
  215. }
  216. }
  217. return array;
  218. }
  219. static bool Fill(object record, ColumnAttribute ca, Type st, object value, bool compatible)
  220. {
  221. // 如果是 NULL 则忽略填充。
  222. if (value.IsNull()) return false;
  223. // 获取属性的类型,必须与 table 中的类型相同。
  224. var prop = ca.Property;
  225. if (prop.PropertyType == st)
  226. {
  227. prop.SetValue(record, value, null);
  228. return true;
  229. }
  230. // 类型不同且不需要兼容时,不填充。
  231. if (!compatible) return false;
  232. // 根据属性类型设置值。
  233. var pt = prop.PropertyType;
  234. if (pt.Equals(typeof(object))) prop.SetValue(record, value, null);
  235. else if (pt.Equals(typeof(byte[]))) prop.SetValue(record, (byte[])value, null);
  236. else if (pt.Equals(typeof(string))) prop.SetValue(record, value.ToString(), null);
  237. else if (pt.Equals(typeof(DateTime))) prop.SetValue(record, value, null);
  238. else if (pt.Equals(typeof(bool))) prop.SetValue(record, NumberUtility.Boolean(value), null);
  239. else if (pt.Equals(typeof(byte))) prop.SetValue(record, NumberUtility.Byte(value), null);
  240. else if (pt.Equals(typeof(sbyte))) prop.SetValue(record, NumberUtility.SByte(value), null);
  241. else if (pt.Equals(typeof(short))) prop.SetValue(record, NumberUtility.Int16(value), null);
  242. else if (pt.Equals(typeof(ushort))) prop.SetValue(record, NumberUtility.UInt16(value), null);
  243. else if (pt.Equals(typeof(int))) prop.SetValue(record, NumberUtility.Int32(value), null);
  244. else if (pt.Equals(typeof(uint))) prop.SetValue(record, NumberUtility.UInt32(value), null);
  245. else if (pt.Equals(typeof(long))) prop.SetValue(record, NumberUtility.Int64(value), null);
  246. else if (pt.Equals(typeof(ulong))) prop.SetValue(record, NumberUtility.UInt64(value), null);
  247. else if (pt.Equals(typeof(float))) prop.SetValue(record, NumberUtility.Single(value), null);
  248. else if (pt.Equals(typeof(double))) prop.SetValue(record, NumberUtility.Double(value), null);
  249. else if (pt.Equals(typeof(decimal))) prop.SetValue(record, NumberUtility.Decimal(value), null);
  250. else if (pt.Equals(typeof(Nullable<DateTime>))) prop.SetValue(record, new Nullable<DateTime>((DateTime)value), null);
  251. else if (pt.Equals(typeof(Nullable<bool>))) prop.SetValue(record, new Nullable<bool>(NumberUtility.Boolean(value)), null);
  252. else if (pt.Equals(typeof(Nullable<byte>))) prop.SetValue(record, new Nullable<byte>(NumberUtility.Byte(value)), null);
  253. else if (pt.Equals(typeof(Nullable<sbyte>))) prop.SetValue(record, new Nullable<sbyte>(NumberUtility.SByte(value)), null);
  254. else if (pt.Equals(typeof(Nullable<short>))) prop.SetValue(record, new Nullable<short>(NumberUtility.Int16(value)), null);
  255. else if (pt.Equals(typeof(Nullable<ushort>))) prop.SetValue(record, new Nullable<int>(NumberUtility.UInt16(value)), null);
  256. else if (pt.Equals(typeof(Nullable<int>))) prop.SetValue(record, new Nullable<int>(NumberUtility.Int32(value)), null);
  257. else if (pt.Equals(typeof(Nullable<uint>))) prop.SetValue(record, new Nullable<uint>(NumberUtility.UInt32(value)), null);
  258. else if (pt.Equals(typeof(Nullable<long>))) prop.SetValue(record, new Nullable<long>(NumberUtility.Int64(value)), null);
  259. else if (pt.Equals(typeof(Nullable<ulong>))) prop.SetValue(record, new Nullable<ulong>(NumberUtility.UInt64(value)), null);
  260. else if (pt.Equals(typeof(Nullable<float>))) prop.SetValue(record, new Nullable<float>(NumberUtility.Single(value)), null);
  261. else if (pt.Equals(typeof(Nullable<double>))) prop.SetValue(record, new Nullable<double>(NumberUtility.Double(value)), null);
  262. else if (pt.Equals(typeof(Nullable<decimal>))) prop.SetValue(record, new Nullable<decimal>(NumberUtility.Decimal(value)), null);
  263. else
  264. {
  265. try
  266. {
  267. prop.SetValue(record, value, null);
  268. return true;
  269. }
  270. catch { }
  271. }
  272. return false;
  273. }
  274. #endregion
  275. #region Record
  276. /// <summary>修复记录属性。</summary>
  277. public static void FixProperties(object record)
  278. {
  279. if (record == null) return;
  280. if (record is IRecord key)
  281. {
  282. if (string.IsNullOrEmpty(key.Key)) key.ResetKey();
  283. }
  284. if (record is IRecordMoment moment)
  285. {
  286. var now = moment.GenerateMoment();
  287. if (string.IsNullOrEmpty(moment.Created)) moment.Created = now;
  288. if (string.IsNullOrEmpty(moment.Updated)) moment.Updated = now;
  289. }
  290. if (record is IRecordStamp stamp)
  291. {
  292. var now = stamp.GenerateStamp();
  293. if (stamp.Created == 0L) stamp.Created = now;
  294. if (stamp.Updated == 0L) stamp.Updated = now;
  295. }
  296. }
  297. /// <summary>设置 Updated 属性。</summary>
  298. /// <returns>TRUE:设置成功;FALSE:设置失败。</returns>
  299. public static bool SetUpdated(object record)
  300. {
  301. if (record == null) return false;
  302. var setted = false;
  303. if (record is IRecordMoment moment)
  304. {
  305. moment.Updated = moment.GenerateMoment();
  306. setted = true;
  307. }
  308. if (record is IRecordStamp stamp)
  309. {
  310. stamp.Updated = stamp.GenerateStamp();
  311. setted = true;
  312. }
  313. return setted;
  314. }
  315. /// <summary>枚举带有 Table 特性的 <typeparamref name="T"/> 派生类型。</summary>
  316. public static Type[] EnumerateRecords<T>() where T : IRecord => EnumerateRecords(typeof(T));
  317. /// <summary>枚举带有 Table 特性的派生类型。</summary>
  318. /// <exception cref="ArgumentNullException"></exception>
  319. public static Type[] EnumerateRecords(Type baseType)
  320. {
  321. if (baseType == null) throw new ArgumentNullException(nameof(baseType));
  322. var assemblies = AppDomain.CurrentDomain.GetAssemblies();
  323. var builder = new ArrayBuilder<Type>();
  324. foreach (var assembly in assemblies)
  325. {
  326. var types = RuntimeUtility.GetTypes(assembly);
  327. foreach (var type in types)
  328. {
  329. if (!EnumerateRecords(type, baseType)) continue;
  330. if (builder.Contains(type)) continue;
  331. builder.Add(type);
  332. }
  333. }
  334. return builder.Export();
  335. }
  336. static bool EnumerateRecords(Type type, Type @base)
  337. {
  338. if (type == null || @base == null) return false;
  339. if (type.IsAbstract) return false;
  340. if (!RuntimeUtility.Contains<TableAttribute>(type, false)) return false;
  341. if (type.Equals(@base)) return true;
  342. if (RuntimeUtility.IsInherits(type, @base)) return true;
  343. return false;
  344. }
  345. #endregion
  346. #region Query
  347. /// <summary>简单查询:取结果中第 0 列所有单元格的文本形式,可指定查询后关闭服务器连接,返回结果中不包含无效文本。</summary>
  348. /// <param name="source">数据库客户端。</param>
  349. /// <param name="sql">用于查询的 SQL 语句。</param>
  350. /// <param name="parameters">SQL 参数。</param>
  351. /// <exception cref="SqlException"></exception>
  352. public static string[] Column(this IDbAdo source, string sql, object parameters = null)
  353. {
  354. if (source == null) return new string[0];
  355. var pool = null as string[];
  356. var rows = 0;
  357. var count = 0;
  358. using (var query = source.Query(sql, parameters))
  359. {
  360. if (!query.Success) throw new SqlException(query, sql);
  361. rows = query.Rows;
  362. if (rows < 1) return new string[0];
  363. pool = new string[rows];
  364. for (int i = 0; i < rows; i++)
  365. {
  366. var cell = TextUtility.Trim(query.Text(i, 0));
  367. if (string.IsNullOrEmpty(cell)) continue;
  368. pool[count] = cell;
  369. count++;
  370. }
  371. }
  372. if (count < 1) return new string[0];
  373. if (count == rows) return pool;
  374. var array = new string[count];
  375. Array.Copy(pool, 0, array, 0, count);
  376. return array;
  377. }
  378. /// <summary>简单查询:取结果中第 0 行、第 0 列单元格中的文本,可指定查询后关闭服务器连接。</summary>
  379. /// <param name="dbClient">数据库客户端。</param>
  380. /// <param name="sql">用于查询的 SQL 语句。</param>
  381. /// <param name="parameters">SQL 参数。</param>
  382. /// <exception cref="ArgumentNullException"></exception>
  383. /// <exception cref="SqlException"></exception>
  384. public static string Cell(this IDbAdo dbClient, string sql, object parameters = null)
  385. {
  386. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  387. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  388. using (var query = dbClient.Query(sql, parameters))
  389. {
  390. if (!query.Success) throw new SqlException(query, sql);
  391. var value = TextUtility.Trim(query.Text(0, 0));
  392. return value;
  393. }
  394. }
  395. /// <summary>查询。</summary>
  396. /// <param name="dbClient">数据库连接。</param>
  397. /// <param name="sql">SQL 语句。</param>
  398. /// <param name="parameters">SQL 参数。</param>
  399. /// <exception cref="ArgumentNullException"></exception>
  400. public static IQuery Query(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  401. {
  402. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  403. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  404. var ps = Parameters(dbClient, sql, parameters);
  405. return dbClient.Query(sql, ps);
  406. }
  407. /// <summary>查询。</summary>
  408. /// <param name="dbClient">数据库连接。</param>
  409. /// <param name="sql">SQL 语句。</param>
  410. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  411. /// <exception cref="ArgumentNullException"></exception>
  412. public static IQuery Query(this IDbAdo dbClient, string sql, object parameters = null)
  413. {
  414. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  415. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  416. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  417. {
  418. var ps = Parameters(dbClient, sql, kvps);
  419. return dbClient.Query(sql, ps);
  420. }
  421. else
  422. {
  423. var ps = ParametersByProperites(dbClient, sql, parameters);
  424. return dbClient.Query(sql, ps);
  425. }
  426. }
  427. /// <summary>执行 SELECT 语句,获取查询结果。</summary>
  428. /// <param name="connection">数据库连接。</param>
  429. /// <param name="transaction">事务。</param>
  430. /// <param name="sql">SQL 语句。</param>
  431. /// <param name="parameters">参数。</param>
  432. /// <param name="timeout">超时秒数。</param>
  433. /// <returns>查询结果。</returns>
  434. public static DataTable Query(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  435. {
  436. if (connection == null) throw new ArgumentNullException(nameof(connection));
  437. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  438. if (connection.State != ConnectionState.Open) connection.Open();
  439. using (var command = connection.CreateCommand())
  440. {
  441. if (transaction != null) command.Transaction = transaction;
  442. if (timeout > 0) command.CommandTimeout = timeout;
  443. command.CommandText = sql;
  444. if (parameters != null)
  445. {
  446. foreach (var parameter in parameters)
  447. {
  448. if (parameter == null) continue;
  449. command.Parameters.Add(parameter);
  450. }
  451. }
  452. using (var reader = command.ExecuteReader())
  453. {
  454. var table = new DataTable();
  455. table.Load(reader);
  456. return table;
  457. }
  458. }
  459. }
  460. /// <summary>查询。</summary>
  461. /// <param name="dbClient">数据库连接。</param>
  462. /// <param name="sql">SQL 语句。</param>
  463. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  464. /// <exception cref="ArgumentNullException"></exception>
  465. /// <exception cref="NotImplementedException"></exception>
  466. public static T[] Query<T>(this IDbOrm dbClient, string sql, object parameters = null) where T : class, new()
  467. {
  468. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  469. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  470. if (dbClient is IDbAdo ado)
  471. {
  472. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  473. {
  474. var ps = Parameters(ado, sql, kvps);
  475. return dbClient.Query<T>(sql, ps);
  476. }
  477. else
  478. {
  479. var ps = ParametersByProperites(ado, sql, parameters);
  480. return dbClient.Query<T>(sql, ps);
  481. }
  482. }
  483. else
  484. {
  485. throw new NotImplementedException($"连接未实现 {nameof(IDbAdo)} 接口,无法创建参数。");
  486. }
  487. }
  488. #endregion
  489. #region Execute
  490. /// <summary>执行 SQL 语句,并加入参数。</summary>
  491. /// <exception cref="ArgumentNullException"></exception>
  492. public static IExecute Execute(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters, bool autoTransaction = false)
  493. {
  494. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  495. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  496. var ps = Parameters(dbClient, sql, parameters);
  497. return dbClient.Execute(sql, ps, autoTransaction);
  498. }
  499. /// <summary>执行 SQL 语句,并加入参数。</summary>
  500. /// <param name="dbClient">数据库连接。</param>
  501. /// <param name="sql">SQL 语句。</param>
  502. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  503. /// <param name="autoTransaction">自动使用事务。</param>
  504. /// <exception cref="ArgumentNullException"></exception>
  505. public static IExecute Execute(this IDbAdo dbClient, string sql, object parameters = null, bool autoTransaction = false)
  506. {
  507. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  508. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  509. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  510. {
  511. var ps = Parameters(dbClient, sql, kvps);
  512. return dbClient.Execute(sql, ps, autoTransaction);
  513. }
  514. {
  515. var ps = ParametersByProperites(dbClient, sql, parameters);
  516. return dbClient.Execute(sql, ps, autoTransaction);
  517. }
  518. }
  519. /// <summary>执行 SQL 语句,获取影响的行数。</summary>
  520. /// <param name="connection">数据库连接。</param>
  521. /// <param name="transaction">事务。</param>
  522. /// <param name="sql">SQL 语句。</param>
  523. /// <param name="parameters">参数。</param>
  524. /// <param name="timeout">超时秒数。</param>
  525. /// <returns>行数。</returns>
  526. public static int Execute(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  527. {
  528. if (connection == null) throw new ArgumentNullException(nameof(connection));
  529. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  530. if (connection.State != ConnectionState.Open) connection.Open();
  531. using (var command = connection.CreateCommand())
  532. {
  533. if (transaction != null) command.Transaction = transaction;
  534. if (timeout > 0) command.CommandTimeout = timeout;
  535. command.CommandText = sql;
  536. if (parameters != null)
  537. {
  538. foreach (var parameter in parameters)
  539. {
  540. if (parameter == null) continue;
  541. command.Parameters.Add(parameter);
  542. }
  543. }
  544. var rows = command.ExecuteNonQuery();
  545. return rows;
  546. }
  547. }
  548. #endregion
  549. #region Transaction
  550. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  551. /// <exception cref="ArgumentNullException"></exception>
  552. /// <exception cref="SqlException"></exception>
  553. public static void InTransaction(this IDbAdo source, Action action)
  554. {
  555. // 检查参数。
  556. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  557. if (action == null) throw new ArgumentNullException(nameof(action), "没有指定要在事物中执行的程序。");
  558. InTransaction<object>(source, () =>
  559. {
  560. action.Invoke();
  561. return null;
  562. });
  563. }
  564. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  565. /// <exception cref="ArgumentNullException"></exception>
  566. /// <exception cref="SqlException"></exception>
  567. public static T InTransaction<T>(this IDbAdo source, Func<T> func)
  568. {
  569. // 检查参数。
  570. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  571. if (func == null) throw new ArgumentNullException(nameof(func), "没有指定要在事物中执行的程序。");
  572. // 已经存在事务。
  573. if (source.Transaction != null) return func.Invoke();
  574. // 启动事务。
  575. var begin = source.Begin();
  576. if (begin.NotEmpty()) throw new SqlException("无法启动事务:" + begin);
  577. var result = default(T);
  578. var success = false;
  579. try
  580. {
  581. // 在事务内运行。
  582. result = func.Invoke();
  583. success = true;
  584. }
  585. finally
  586. {
  587. if (success)
  588. {
  589. // 执行成功,提交事务。
  590. var commit = source.Commit();
  591. if (!string.IsNullOrEmpty(commit)) throw new SqlException(commit);
  592. }
  593. else
  594. {
  595. // 执行失败,回滚事务。
  596. try { source.Rollback(); } catch { }
  597. }
  598. }
  599. return result;
  600. }
  601. #endregion
  602. #region Parameter
  603. /// <exception cref="ArgumentNullException"></exception>
  604. static List<IDataParameter> ParametersByProperites(IDbAdo dbClient, string sql, object parameters)
  605. {
  606. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  607. if (parameters == null) return null;
  608. var lsql = sql.Lower();
  609. var type = parameters.GetType();
  610. var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  611. var count = properties.Length;
  612. var dict = new Dictionary<string, object>(count);
  613. for (var i = 0; i < count; i++)
  614. {
  615. var property = properties[i];
  616. // 属性必须能够获取值。
  617. var getter = property.GetGetMethod();
  618. if (getter == null) continue;
  619. // 属性值必须有效。
  620. var name = property.Name;
  621. if (name.IsEmpty()) continue;
  622. // 属性不可重复。
  623. if (!name.StartsWith("@")) name = "@" + name;
  624. if (dict.ContainsKey(name)) continue;
  625. // SQL 语句中必须包含此参数。
  626. var lname = name.Lower();
  627. if (!lsql.Contains(lname)) continue;
  628. // 加入字典。
  629. var value = getter.Invoke(parameters, null);
  630. dict.Add(name, value);
  631. }
  632. if (dict.Count < 1) return null;
  633. var ps = new List<IDataParameter>();
  634. foreach (var kvp in dict)
  635. {
  636. var p = dbClient.Parameter(kvp.Key, kvp.Value);
  637. ps.Add(p);
  638. }
  639. return ps;
  640. }
  641. /// <exception cref="ArgumentNullException"></exception>
  642. static List<IDataParameter> Parameters(IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  643. {
  644. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  645. if (parameters == null) return null;
  646. var lsql = sql.Lower();
  647. var names = new List<string>(20);
  648. var ps = new List<IDataParameter>(20);
  649. foreach (var kvp in parameters)
  650. {
  651. var name = kvp.Key;
  652. if (name.IsEmpty()) continue;
  653. // 属性不可重复。
  654. if (!name.StartsWith("@")) name = "@" + name;
  655. if (names.Contains(name)) continue;
  656. // SQL 语句中必须包含此参数。
  657. var lname = name.Lower();
  658. if (!lsql.Contains(lname)) continue;
  659. var p = dbClient.Parameter(name, kvp.Value);
  660. ps.Add(p);
  661. names.Add(name);
  662. }
  663. return ps;
  664. }
  665. #endregion
  666. #region SQL
  667. /// <summary>对文本转义,符合 SQL 安全性。可根据字段类型限制 UTF-8 字节数,默认为 0 时不限制字节数。</summary>
  668. public static string Escape(this string text, int bytes = 0)
  669. {
  670. if (text.IsEmpty()) return "";
  671. var t = text ?? "";
  672. t = t.Replace("\\", "\\\\");
  673. t = t.Replace("'", "\\'");
  674. t = t.Replace("\n", "\\n");
  675. t = t.Replace("\r", "\\r");
  676. t = t.Replace("\b", "\\b");
  677. t = t.Replace("\t", "\\t");
  678. t = t.Replace("\f", "\\f");
  679. if (bytes > 5)
  680. {
  681. if (t.Bytes(Encoding.UTF8).Length > bytes)
  682. {
  683. while (true)
  684. {
  685. t = t.Substring(0, t.Length - 1);
  686. if (t.Bytes(Encoding.UTF8).Length <= (bytes - 4)) break;
  687. }
  688. t = t + " ...";
  689. }
  690. }
  691. return t;
  692. }
  693. /// <summary>限定名称文本,只允许包含字母、数字和下划线。</summary>
  694. public static string SafeName(this string name) => TextUtility.Restrict(name, "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  695. #endregion
  696. #region 数据模型 -> DataTable
  697. /// <summary>将多个实体元素转换为 DataTable。</summary>
  698. /// <typeparam name="T">实体元素的类型。</typeparam>
  699. /// <param name="items">实体元素。</param>
  700. /// <param name="tableName">设置 <see cref="DataTable"/> 的名称。</param>
  701. /// <exception cref="ArgumentNullException"></exception>
  702. /// <exception cref="DuplicateNameException"></exception>
  703. /// <exception cref="InvalidExpressionException"></exception>
  704. public static DataTable DataTable<T>(this IEnumerable<T> items, string tableName = null)
  705. {
  706. if (items == null) throw new ArgumentNullException(nameof(items));
  707. // 解析表结构。
  708. var it = typeof(T);
  709. var ts = TableStructure.Parse(it, true, true);
  710. if (ts == null || ts.Columns == null || ts.Columns.Length < 1)
  711. {
  712. foreach (var item in items)
  713. {
  714. if (item == null) continue;
  715. var itemType = item.GetType();
  716. ts = TableStructure.Parse(itemType, true, true);
  717. if (ts == null) throw new TypeLoadException($"无法解析 {itemType.FullName} 的结构。");
  718. it = itemType;
  719. break;
  720. }
  721. if (ts == null) throw new TypeLoadException($"无法解析 {it.FullName} 的结构。");
  722. }
  723. var cas = ts.Columns;
  724. var width = cas.Length;
  725. if (width < 1) throw new TypeLoadException($"类型 {it.FullName} 的结构中没有列。");
  726. // 初始化列。
  727. var table = new DataTable();
  728. var pis = new PropertyInfo[width];
  729. var fts = new Type[width];
  730. for (var i = 0; i < width; i++)
  731. {
  732. var ca = cas[i];
  733. var pi = ca.Property;
  734. var pt = pi.PropertyType;
  735. pis[i] = pi;
  736. var ft = pt;
  737. if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
  738. {
  739. pt.GetGenericArguments();
  740. ft = Nullable.GetUnderlyingType(pt);
  741. }
  742. fts[i] = ft;
  743. var column = new DataColumn(ca.Field, ft);
  744. column.AllowDBNull = true;
  745. table.Columns.Add(column);
  746. }
  747. // 添加行。
  748. foreach (var item in items)
  749. {
  750. if (item == null) continue;
  751. var values = new ArrayBuilder<object>(width);
  752. for (var i = 0; i < width; i++)
  753. {
  754. var value = pis[i].GetValue(item, null);
  755. if (value is DateTime dt)
  756. {
  757. if (dt.Year < 1753)
  758. {
  759. values.Add(DBNull.Value);
  760. continue;
  761. }
  762. }
  763. values.Add(value);
  764. }
  765. table.Rows.Add(values.Export());
  766. }
  767. if (tableName.NotEmpty()) table.TableName = tableName;
  768. else if (ts.TableName.NotEmpty()) table.TableName = ts.TableName;
  769. return table;
  770. }
  771. #endregion
  772. #region DataTable 序列化
  773. /// <summary>转换 <see cref="System.Data.DataTable"/> 到 <see cref="ObjectSet{T}"/> 数组,每行记录为一个 ObjectSet 对象。</summary>
  774. /// <returns>当参数 table 无效时返回 0 长度的 <see cref="ObjectSet{T}"/> 数组。</returns>
  775. public static ObjectSet[] ObjectSet(this DataTable table)
  776. {
  777. if (table == null) return new ObjectSet[0];
  778. var columns = table.Columns.Count;
  779. var fields = new string[columns];
  780. for (var c = 0; c < columns; c++) fields[c] = table.Columns[c].ColumnName;
  781. var rows = table.Rows.Count;
  782. var dicts = new Dictionary<string, object>[rows];
  783. for (var r = 0; r < table.Rows.Count; r++)
  784. {
  785. var dict = new Dictionary<string, object>(columns);
  786. for (var c = 0; c < columns; c++)
  787. {
  788. var field = fields[c];
  789. if (string.IsNullOrEmpty(field)) continue;
  790. if (dict.ContainsKey(field)) continue;
  791. var v = table.Rows[r][c];
  792. if (v.IsNull()) v = null;
  793. dict.Add(field, v);
  794. }
  795. dicts[r] = dict;
  796. }
  797. var oss = new ObjectSet[rows];
  798. for (var i = 0; i < rows; i++) oss[i] = new ObjectSet(dicts[i]);
  799. return oss;
  800. }
  801. /// <summary>转换为 Json 对象。</summary>
  802. public static Json ToJson(this DataTable table, Func<DateTime, string> dateTimeFormatter = null)
  803. {
  804. if (table == null) return null;
  805. var columns = ToJson(table.Columns);
  806. var rows = ToJson(table.Rows, dateTimeFormatter);
  807. var jsonObject = Json.NewObject();
  808. jsonObject.SetProperty("columns", columns);
  809. jsonObject.SetProperty("rows", rows);
  810. return jsonObject;
  811. }
  812. /// <summary>转换为 Json 对象。</summary>
  813. public static Json ToJson(this DataColumnCollection columns)
  814. {
  815. if (columns == null) return null;
  816. var json = Json.NewArray();
  817. var count = columns.Count;
  818. for (var c = 0; c < count; c++)
  819. {
  820. var dc = columns[c];
  821. var column = Json.NewObject();
  822. column.SetProperty("name", dc.ColumnName);
  823. column.SetProperty("type", dc.DataType.FullName);
  824. json.AddItem(column);
  825. }
  826. return json;
  827. }
  828. /// <summary>转换为 Json 对象。</summary>
  829. public static Json ToJson(this DataRowCollection rows, Func<DateTime, object> dateTimeFormatter = null)
  830. {
  831. if (rows == null) return null;
  832. var json = Json.NewArray();
  833. var count = rows.Count;
  834. for (var r = 0; r < count; r++)
  835. {
  836. json.AddItem(ToJson(rows[r], dateTimeFormatter));
  837. }
  838. return json;
  839. }
  840. /// <summary>转换为 Json 对象。</summary>
  841. public static Json ToJson(this DataRow row, Func<DateTime, object> dateTimeFormatter = null)
  842. {
  843. if (row == null) return null;
  844. var cells = row.ItemArray;
  845. var count = cells.Length;
  846. var json = Json.NewArray();
  847. for (var c = 0; c < count; c++)
  848. {
  849. var value = cells[c];
  850. if (value == null || value.Equals(DBNull.Value))
  851. {
  852. json.AddItem();
  853. continue;
  854. }
  855. if (value is DateTime vDateTime)
  856. {
  857. if (dateTimeFormatter == null)
  858. {
  859. json.AddItem(Json.SerializeDateTime(vDateTime));
  860. continue;
  861. }
  862. else
  863. {
  864. value = dateTimeFormatter.Invoke(vDateTime);
  865. if (value == null || value.Equals(DBNull.Value))
  866. {
  867. json.AddItem();
  868. continue;
  869. }
  870. }
  871. }
  872. if (value is string @string) json.AddItem(@string);
  873. else if (value is byte @byte) json.AddItem(@byte);
  874. else if (value is short @short) json.AddItem(@short);
  875. else if (value is int @int) json.AddItem(@int);
  876. else if (value is long @long) json.AddItem(@long);
  877. else if (value is float @float) json.AddItem(@float);
  878. else if (value is double @double) json.AddItem(@double);
  879. else if (value is decimal @decimal) json.AddItem(@decimal);
  880. else if (value is bool @bool) json.AddItem(@bool);
  881. else if (value is byte[] bytes) json.AddItem(bytes.Base64());
  882. else json.AddItem(TextUtility.Text(value));
  883. }
  884. return json;
  885. }
  886. /// <summary>转换 <see cref="DataTable"/> 为 CSV 文本,不存在表时返回 NULL 值。可指定是否包含表头。</summary>
  887. public static string Csv(DataTable table, bool withHead = false)
  888. {
  889. if (table == null) return null;
  890. var columns = table.Columns.Count;
  891. if (columns < 1) return "";
  892. var sb = new StringBuilder();
  893. if (withHead)
  894. {
  895. for (var c = 0; c < columns; c++)
  896. {
  897. var v = table.Columns[c].ColumnName;
  898. CsvCell(sb, c, v);
  899. }
  900. }
  901. var rows = table.Rows.Count;
  902. for (var r = 0; r < rows; r++)
  903. {
  904. var row = table.Rows[r];
  905. if (withHead || r > 0) sb.Append("\r\n");
  906. for (var c = 0; c < columns; c++) CsvCell(sb, c, row[c]);
  907. }
  908. return sb.ToString();
  909. }
  910. private static void CsvCell(StringBuilder sb, int c, object v)
  911. {
  912. if (c > 0) sb.Append(",");
  913. if (v == null || v.Equals(DBNull.Value)) return;
  914. if (v is bool @bool)
  915. {
  916. sb.Append(@bool ? "TRUE" : "FALSE");
  917. return;
  918. }
  919. if (v is DateTime @datetime)
  920. {
  921. sb.Append(@datetime.Lucid());
  922. return;
  923. }
  924. if (v is byte || v is sbyte || v is short || v is ushort || v is int || v is uint || v is long || v is ulong || v is float || v is double || v is decimal)
  925. {
  926. sb.Append(v.ToString());
  927. return;
  928. }
  929. if (v is char)
  930. {
  931. sb.Append((char)v);
  932. return;
  933. }
  934. var s = (v is string @string) ? @string : v.ToString();
  935. var length = s.Length;
  936. if (length < 1) return;
  937. var quote = false;
  938. var comma = false;
  939. var newline = false;
  940. for (var i = 0; i < length; i++)
  941. {
  942. var @char = s[i];
  943. if (@char == '\"') quote = true;
  944. else if (@char == ',') comma = true;
  945. else if (@char == '\r') newline = false;
  946. else if (@char == '\n') newline = false;
  947. }
  948. if (quote || comma || newline)
  949. {
  950. sb.Append("\"");
  951. s = s.Replace("\"", "\"\"");
  952. sb.Append(s);
  953. sb.Append("\"");
  954. }
  955. else sb.Append(s);
  956. }
  957. #endregion
  958. #region DataTable 快捷操作
  959. /// <summary>获取默认表中指定单元格的内容。</summary>
  960. /// <param name="table">数据表。</param>
  961. /// <param name="rowIndex">行索引,从 0 开始。</param>
  962. /// <param name="columnIndex">列索引,从 0 开始。</param>
  963. public static object Value(this DataTable table, int rowIndex, int columnIndex)
  964. {
  965. if (table != null)
  966. {
  967. if (rowIndex >= 0 && rowIndex < table.Rows.Count)
  968. {
  969. if (columnIndex >= 0 && columnIndex < table.Columns.Count)
  970. {
  971. var value = table.Rows[rowIndex][columnIndex];
  972. if (value == null || value.Equals(DBNull.Value)) return null;
  973. return value;
  974. }
  975. }
  976. }
  977. return null;
  978. }
  979. /// <summary>获取默认表中指定单元的内容。</summary>
  980. /// <param name="table">数据表。</param>
  981. /// <param name="rowIndex">行索引,从 0 开始。</param>
  982. /// <param name="columnName">列名称/字段名称,此名称不区分大小写。</param>
  983. public static object Value(this DataTable table, int rowIndex, string columnName)
  984. {
  985. if (table != null && !string.IsNullOrEmpty(columnName))
  986. {
  987. if ((rowIndex < table.Rows.Count) && (rowIndex >= 0))
  988. {
  989. try
  990. {
  991. var value = table.Rows[rowIndex][columnName];
  992. if (value == null || value.Equals(DBNull.Value)) return null;
  993. return value;
  994. }
  995. catch { }
  996. }
  997. }
  998. return null;
  999. }
  1000. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1001. public static Class<DateTime> DateTime(this DataTable table, int row, int column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  1002. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1003. public static Class<DateTime> DateTime(this DataTable table, int row, string column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  1004. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1005. public static Int32 Int32(this DataTable table, int row, int column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  1006. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1007. public static Int32 Int32(this DataTable table, int row, string column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  1008. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1009. public static Int64 Int64(this DataTable table, int row, int column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  1010. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1011. public static Int64 Int64(this DataTable table, int row, string column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  1012. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1013. public static Decimal Decimal(this DataTable table, int row, int column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  1014. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1015. public static Decimal Decimal(this DataTable table, int row, string column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  1016. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>>
  1017. public static Double Double(this DataTable table, int row, int column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  1018. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>>
  1019. public static Double Double(this DataTable table, int row, string column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  1020. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1021. public static string Text(this DataTable table, int row, int column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  1022. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1023. public static string Text(this DataTable table, int row, string column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  1024. #endregion
  1025. #region Dynamic
  1026. #if NET40_OR_GREATER
  1027. /// <summary>转换 ObjectSet 数组为 dynamic 数组。</summary>
  1028. public static dynamic[] Dynamic(this ObjectSet[] oss)
  1029. {
  1030. if (oss == null) return new dynamic[0];
  1031. var eos = oss.Expando();
  1032. var ds = new dynamic[eos.Length];
  1033. eos.CopyTo(ds, 0);
  1034. return ds;
  1035. }
  1036. #endif
  1037. #endregion
  1038. #region 表达式计算
  1039. /// <summary>计算文本表达式。</summary>
  1040. public static object Compute(string expression)
  1041. {
  1042. using (var table = new DataTable())
  1043. {
  1044. var result = table.Compute(expression, null);
  1045. if (result.IsNull()) return null;
  1046. return result;
  1047. }
  1048. }
  1049. #endregion
  1050. }
  1051. }