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.

1652 lines
74 KiB

5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
3 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
5 years ago
5 years ago
5 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
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 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
4 years ago
4 years ago
3 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
4 years ago
4 years ago
3 years ago
4 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
4 years ago
3 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
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 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
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
4 years ago
4 years ago
4 years ago
3 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
4 years ago
4 years ago
3 years ago
4 years ago
3 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
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices.ComTypes;
  6. using System.Text;
  7. namespace Apewer.Source
  8. {
  9. /// <summary>ORM 帮助程序。</summary>
  10. public static class SourceUtility
  11. {
  12. #region ORM
  13. /// <summary>读取所有行,生成列表。</summary>
  14. public static T[] Fill<T>(this IQuery query) where T : class, new()
  15. {
  16. var objects = Fill(query, typeof(T));
  17. var array = CollectionUtility.As<object, T>(objects);
  18. return array;
  19. }
  20. /// <summary>读取所有行填充到 T,组成 T[]。</summary>
  21. /// <exception cref="ArgumentNullException"></exception>
  22. /// <exception cref="ArgumentException"></exception>
  23. public static object[] Fill(this IQuery query, Type model)
  24. {
  25. if (query == null) return new object[0];
  26. if (query.Table == null) return new object[0];
  27. if (model == null) return new object[0];
  28. return Fill(query.Table, model);
  29. }
  30. /// <summary>将 Query 的行,填充到模型实体。</summary>
  31. /// <remarks>填充失败时返回 NULL 值。</remarks>
  32. /// <exception cref="Exception"></exception>
  33. public static object FillRow(IQuery query, int rowIndex, Type model, TableStructure structure) => FillRow(query?.Table, rowIndex, model, structure);
  34. /// <summary>将 Query 的行,填充到模型实体。</summary>
  35. /// <remarks>填充失败时返回 NULL 值。</remarks>
  36. /// <exception cref="Exception"></exception>
  37. public static object FillRow(DataTable table, int rowIndex, Type model, TableStructure structure)
  38. {
  39. // 检查参数。
  40. if (table == null || model == null || structure == null) return null;
  41. if (rowIndex < 0 || rowIndex >= table.Rows.Count) return null;
  42. if (!RuntimeUtility.CanNew(model)) return null;
  43. // 变量别名。
  44. var ts = structure;
  45. var r = rowIndex;
  46. var columns = ts.Columns;
  47. // 检查模型的属性,按属性从表中取相应的列。
  48. var record = Activator.CreateInstance(model);
  49. var properties = model.GetProperties();
  50. foreach (var property in properties)
  51. {
  52. // 在表结构中检查,是否包含此属性,并获取 ColumnAttribute 中的 Field。
  53. var field = null as string;
  54. for (var j = 0; j < columns.Length; j++)
  55. {
  56. if (columns[j].PropertyName == property.Name)
  57. {
  58. field = columns[j].Field;
  59. break;
  60. }
  61. }
  62. if (field == null)
  63. {
  64. if (ts && ts.Table.AllProperties) continue;
  65. field = property.Name;
  66. }
  67. var value = table.Rows[r][field];
  68. if (value != null && value.Equals(DBNull.Value)) value = null;
  69. var setted = Set(record, property, value);
  70. }
  71. return record;
  72. }
  73. static bool Set(object record, PropertyInfo property, object value)
  74. {
  75. // 读取值。
  76. if (value == null) return false;
  77. if (value.Equals(DBNull.Value)) return false;
  78. // 必须有 setter 访问器。
  79. var setter = property.GetSetMethod();
  80. if (setter == null) return false;
  81. // 根据属性类型设置值。
  82. var pt = property.PropertyType;
  83. if (pt.Equals(typeof(object))) setter.Invoke(record, new object[] { value });
  84. else if (pt.Equals(typeof(byte[]))) setter.Invoke(record, new object[] { (byte[])value });
  85. else if (pt.Equals(typeof(string))) setter.Invoke(record, new object[] { value.ToString() });
  86. else if (pt.Equals(typeof(DateTime))) setter.Invoke(record, new object[] { value });
  87. else if (pt.Equals(typeof(bool))) setter.Invoke(record, new object[] { NumberUtility.Boolean(value) });
  88. else if (pt.Equals(typeof(byte))) setter.Invoke(record, new object[] { NumberUtility.Byte(value) });
  89. else if (pt.Equals(typeof(sbyte))) setter.Invoke(record, new object[] { NumberUtility.SByte(value) });
  90. else if (pt.Equals(typeof(short))) setter.Invoke(record, new object[] { NumberUtility.Int16(value) });
  91. else if (pt.Equals(typeof(ushort))) setter.Invoke(record, new object[] { NumberUtility.UInt16(value) });
  92. else if (pt.Equals(typeof(int))) setter.Invoke(record, new object[] { NumberUtility.Int32(value) });
  93. else if (pt.Equals(typeof(uint))) setter.Invoke(record, new object[] { NumberUtility.UInt32(value) });
  94. else if (pt.Equals(typeof(long))) setter.Invoke(record, new object[] { NumberUtility.Int64(value) });
  95. else if (pt.Equals(typeof(ulong))) setter.Invoke(record, new object[] { NumberUtility.UInt64(value) });
  96. else if (pt.Equals(typeof(float))) setter.Invoke(record, new object[] { NumberUtility.Single(value) });
  97. else if (pt.Equals(typeof(double))) setter.Invoke(record, new object[] { NumberUtility.Double(value) });
  98. else if (pt.Equals(typeof(decimal))) setter.Invoke(record, new object[] { NumberUtility.Decimal(value) });
  99. #if !NET20
  100. else if (pt.Equals(typeof(Nullable<DateTime>))) setter.Invoke(record, new object[] { new Nullable<DateTime>((DateTime)value) });
  101. else if (pt.Equals(typeof(Nullable<bool>))) setter.Invoke(record, new object[] { new Nullable<bool>(NumberUtility.Boolean(value)) });
  102. else if (pt.Equals(typeof(Nullable<byte>))) setter.Invoke(record, new object[] { new Nullable<byte>(NumberUtility.Byte(value)) });
  103. else if (pt.Equals(typeof(Nullable<sbyte>))) setter.Invoke(record, new object[] { new Nullable<sbyte>(NumberUtility.SByte(value)) });
  104. else if (pt.Equals(typeof(Nullable<short>))) setter.Invoke(record, new object[] { new Nullable<short>(NumberUtility.Int16(value)) });
  105. else if (pt.Equals(typeof(Nullable<ushort>))) setter.Invoke(record, new object[] { new Nullable<int>(NumberUtility.UInt16(value)) });
  106. else if (pt.Equals(typeof(Nullable<int>))) setter.Invoke(record, new object[] { new Nullable<int>(NumberUtility.Int32(value)) });
  107. else if (pt.Equals(typeof(Nullable<uint>))) setter.Invoke(record, new object[] { new Nullable<uint>(NumberUtility.UInt32(value)) });
  108. else if (pt.Equals(typeof(Nullable<long>))) setter.Invoke(record, new object[] { new Nullable<long>(NumberUtility.Int64(value)) });
  109. else if (pt.Equals(typeof(Nullable<ulong>))) setter.Invoke(record, new object[] { new Nullable<ulong>(NumberUtility.UInt64(value)) });
  110. else if (pt.Equals(typeof(Nullable<float>))) setter.Invoke(record, new object[] { new Nullable<float>(NumberUtility.Single(value)) });
  111. else if (pt.Equals(typeof(Nullable<double>))) setter.Invoke(record, new object[] { new Nullable<double>(NumberUtility.Double(value)) });
  112. else if (pt.Equals(typeof(Nullable<decimal>))) setter.Invoke(record, new object[] { new Nullable<decimal>(NumberUtility.Decimal(value)) });
  113. #endif
  114. else
  115. {
  116. try
  117. {
  118. setter.Invoke(record, new object[] { value });
  119. return true;
  120. }
  121. catch { }
  122. }
  123. return false;
  124. }
  125. /// <summary>解析 DataTable,填充没行到到指定的类型中,形成数组。</summary>
  126. /// <param name="table">将要读取的表。</param>
  127. /// <param name="compatible">当类型不同时,尝试转换以兼容。</param>
  128. /// <returns>由指定类型组成的数组。</returns>
  129. /// <exception cref="ArgumentNullException"></exception>
  130. /// <exception cref="ArgumentException"></exception>
  131. public static T[] Fill<T>(this DataTable table, bool compatible = true)
  132. {
  133. if (table == null) throw new ArgumentNullException(nameof(table), $"参数 {table} 无效。");
  134. var objects = Fill(table, typeof(T), compatible);
  135. var count = objects.Length;
  136. var array = new T[count];
  137. for (var i = 0; i < count; i++) array[i] = (T)objects[i];
  138. return array;
  139. }
  140. /// <summary>解析 DataTable,填充没行到到指定的类型中,形成数组。</summary>
  141. /// <param name="table">将要读取的表。</param>
  142. /// <param name="model">要填充的目标类型,必须是可实例化的引用类型。</param>
  143. /// <param name="compatible">当类型不同时,尝试转换以兼容。</param>
  144. /// <returns>由指定类型组成的数组。</returns>
  145. /// <exception cref="ArgumentNullException"></exception>
  146. /// <exception cref="ArgumentException"></exception>
  147. public static object[] Fill(this DataTable table, Type model, bool compatible = true)
  148. {
  149. if (table == null) throw new ArgumentNullException(nameof(table), $"参数 {table} 无效。");
  150. if (model == null) throw new ArgumentNullException(nameof(model), $"参数 {model} 无效。");
  151. // 检查模型是否允许填充。
  152. var ts = TableStructure.Parse(model, true, true);
  153. if (ts == null) throw new ArgumentException($"无法填充到类型 {model.FullName} 中。");
  154. // 检查行数。
  155. var rows = table.Rows;
  156. var rowsCount = rows.Count;
  157. if (rowsCount < 1) return new object[0];
  158. // 确定数组。
  159. var array = new object[rowsCount];
  160. for (var i = 0; i < rowsCount; i++) array[i] = Activator.CreateInstance(model, true);
  161. // 检查列数。
  162. var columns = table.Columns;
  163. var columnsCount = columns.Count;
  164. if (columnsCount < 1) return array;
  165. // 解析表头,仅保留有名称的列。
  166. var sc = 0;
  167. var sfs = new string[columnsCount];
  168. var sts = new Type[columnsCount];
  169. var sis = new int[columnsCount];
  170. for (var i = 0; i < columnsCount; i++)
  171. {
  172. var column = columns[i];
  173. var key = column.ColumnName.Lower();
  174. if (string.IsNullOrEmpty(key)) continue;
  175. if (sfs.Contains(key)) continue;
  176. sfs[sc] = key;
  177. sts[sc] = column.DataType;
  178. sis[sc] = i;
  179. sc++;
  180. }
  181. if (sc < 1) return array;
  182. // 解析模型列。
  183. var cas = ts.Fillable;
  184. var dc = 0;
  185. var dfs = new string[cas.Length];
  186. var dts = new ColumnAttribute[cas.Length];
  187. for (var i = 0; i < cas.Length; i++)
  188. {
  189. var ca = cas[i];
  190. var key = ca.Field.Lower();
  191. if (string.IsNullOrEmpty(key)) continue;
  192. if (dfs.Contains(key)) continue;
  193. dfs[dc] = key;
  194. dts[dc] = ca;
  195. dc++;
  196. }
  197. if (dc < 1) return array;
  198. // 遍历、填充。
  199. for (var r = 0; r < rowsCount; r++)
  200. {
  201. var record = array[r];
  202. // 遍历 table 的列。
  203. for (var s = 0; s < sc; s++)
  204. {
  205. var sf = sfs[s];
  206. // 遍历 model 的列。
  207. for (var d = 0; d < dc; d++)
  208. {
  209. var df = dfs[d];
  210. if (df != sf) continue;
  211. // 取值、填充。
  212. var value = rows[r][sis[s]];
  213. Fill(record, dts[d], sts[s], value, compatible);
  214. break;
  215. }
  216. }
  217. }
  218. return array;
  219. }
  220. static bool Fill(object record, ColumnAttribute ca, Type st, object value, bool compatible)
  221. {
  222. // 如果是 NULL 则忽略填充。
  223. if (value.IsNull()) return false;
  224. // 获取属性的类型,必须与 table 中的类型相同。
  225. var prop = ca.Property;
  226. if (prop.PropertyType == st)
  227. {
  228. prop.SetValue(record, value, null);
  229. return true;
  230. }
  231. // 类型不同且不需要兼容时,不填充。
  232. if (!compatible) return false;
  233. // 根据属性类型设置值。
  234. var pt = prop.PropertyType;
  235. if (pt.Equals(typeof(object))) prop.SetValue(record, value, null);
  236. else if (pt.Equals(typeof(byte[]))) prop.SetValue(record, (byte[])value, null);
  237. else if (pt.Equals(typeof(string))) prop.SetValue(record, value.ToString(), null);
  238. else if (pt.Equals(typeof(DateTime))) prop.SetValue(record, value, null);
  239. else if (pt.Equals(typeof(bool))) prop.SetValue(record, NumberUtility.Boolean(value), null);
  240. else if (pt.Equals(typeof(byte))) prop.SetValue(record, NumberUtility.Byte(value), null);
  241. else if (pt.Equals(typeof(sbyte))) prop.SetValue(record, NumberUtility.SByte(value), null);
  242. else if (pt.Equals(typeof(short))) prop.SetValue(record, NumberUtility.Int16(value), null);
  243. else if (pt.Equals(typeof(ushort))) prop.SetValue(record, NumberUtility.UInt16(value), null);
  244. else if (pt.Equals(typeof(int))) prop.SetValue(record, NumberUtility.Int32(value), null);
  245. else if (pt.Equals(typeof(uint))) prop.SetValue(record, NumberUtility.UInt32(value), null);
  246. else if (pt.Equals(typeof(long))) prop.SetValue(record, NumberUtility.Int64(value), null);
  247. else if (pt.Equals(typeof(ulong))) prop.SetValue(record, NumberUtility.UInt64(value), null);
  248. else if (pt.Equals(typeof(float))) prop.SetValue(record, NumberUtility.Single(value), null);
  249. else if (pt.Equals(typeof(double))) prop.SetValue(record, NumberUtility.Double(value), null);
  250. else if (pt.Equals(typeof(decimal))) prop.SetValue(record, NumberUtility.Decimal(value), null);
  251. else if (pt.Equals(typeof(Nullable<DateTime>))) prop.SetValue(record, new Nullable<DateTime>((DateTime)value), null);
  252. else if (pt.Equals(typeof(Nullable<bool>))) prop.SetValue(record, new Nullable<bool>(NumberUtility.Boolean(value)), null);
  253. else if (pt.Equals(typeof(Nullable<byte>))) prop.SetValue(record, new Nullable<byte>(NumberUtility.Byte(value)), null);
  254. else if (pt.Equals(typeof(Nullable<sbyte>))) prop.SetValue(record, new Nullable<sbyte>(NumberUtility.SByte(value)), null);
  255. else if (pt.Equals(typeof(Nullable<short>))) prop.SetValue(record, new Nullable<short>(NumberUtility.Int16(value)), null);
  256. else if (pt.Equals(typeof(Nullable<ushort>))) prop.SetValue(record, new Nullable<int>(NumberUtility.UInt16(value)), null);
  257. else if (pt.Equals(typeof(Nullable<int>))) prop.SetValue(record, new Nullable<int>(NumberUtility.Int32(value)), null);
  258. else if (pt.Equals(typeof(Nullable<uint>))) prop.SetValue(record, new Nullable<uint>(NumberUtility.UInt32(value)), null);
  259. else if (pt.Equals(typeof(Nullable<long>))) prop.SetValue(record, new Nullable<long>(NumberUtility.Int64(value)), null);
  260. else if (pt.Equals(typeof(Nullable<ulong>))) prop.SetValue(record, new Nullable<ulong>(NumberUtility.UInt64(value)), null);
  261. else if (pt.Equals(typeof(Nullable<float>))) prop.SetValue(record, new Nullable<float>(NumberUtility.Single(value)), null);
  262. else if (pt.Equals(typeof(Nullable<double>))) prop.SetValue(record, new Nullable<double>(NumberUtility.Double(value)), null);
  263. else if (pt.Equals(typeof(Nullable<decimal>))) prop.SetValue(record, new Nullable<decimal>(NumberUtility.Decimal(value)), null);
  264. else
  265. {
  266. try
  267. {
  268. prop.SetValue(record, value, null);
  269. return true;
  270. }
  271. catch { }
  272. }
  273. return false;
  274. }
  275. #endregion
  276. #region Record
  277. /// <summary>修复记录属性。</summary>
  278. public static void FixProperties(object record)
  279. {
  280. if (record == null) return;
  281. if (record is IRecord key)
  282. {
  283. if (string.IsNullOrEmpty(key.Key)) key.ResetKey();
  284. }
  285. if (record is IRecordMoment moment)
  286. {
  287. var now = moment.GenerateMoment();
  288. if (string.IsNullOrEmpty(moment.Created)) moment.Created = now;
  289. if (string.IsNullOrEmpty(moment.Updated)) moment.Updated = now;
  290. }
  291. if (record is IRecordStamp stamp)
  292. {
  293. var now = stamp.GenerateStamp();
  294. if (stamp.Created == 0L) stamp.Created = now;
  295. if (stamp.Updated == 0L) stamp.Updated = now;
  296. }
  297. // 类型缓存
  298. var DateTimeType = typeof(DateTime);
  299. var MinDateTime = new DateTime(1753, 1, 1, 0, 0, 0, 0);
  300. var MaxDateTime = new DateTime(9999, 12, 31, 23, 59, 59, 997);
  301. var NullableDateTimeType = typeof(DateTime?);
  302. var StringType = typeof(string);
  303. #if DEBUG // 待测试
  304. // 遍历字段
  305. var recordType = record.GetType();
  306. var tableStructure = TableStructure.Parse(recordType);
  307. foreach (var column in tableStructure.Columns)
  308. {
  309. // 字符串 NOT NULL
  310. if (column.Property.PropertyType.Equals(StringType))
  311. {
  312. var value = column.Property.GetGetMethod().Invoke(record, null);
  313. if (value == null)
  314. {
  315. var notNull = RuntimeUtility.GetAttribute<NotNullAttribute>(column.Property);
  316. if (notNull != null)
  317. {
  318. column.Property.GetSetMethod().Invoke(record, new object[] { "" });
  319. }
  320. }
  321. continue;
  322. }
  323. // DateTime
  324. // min = 1753-01-01 00:00:00.000
  325. // max = 9999-12-31 23:59:59.997
  326. if (column.Property.PropertyType.Equals(DateTimeType))
  327. {
  328. var value = (DateTime)column.Property.GetGetMethod().Invoke(record, null);
  329. if (value < MinDateTime)
  330. {
  331. column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime });
  332. }
  333. else if (value > MaxDateTime)
  334. {
  335. column.Property.GetSetMethod().Invoke(record, new object[] { MaxDateTime });
  336. }
  337. continue;
  338. }
  339. if (column.Property.PropertyType.Equals(NullableDateTimeType))
  340. {
  341. var value = (DateTime?)column.Property.GetGetMethod().Invoke(record, null);
  342. if (value == null)
  343. {
  344. var notNull = RuntimeUtility.GetAttribute<NotNullAttribute>(column.Property);
  345. if (notNull != null)
  346. {
  347. column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime });
  348. }
  349. }
  350. else
  351. {
  352. if (value < MinDateTime)
  353. {
  354. column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime });
  355. }
  356. else if (value > MaxDateTime)
  357. {
  358. column.Property.GetSetMethod().Invoke(record, new object[] { MaxDateTime });
  359. }
  360. }
  361. continue;
  362. }
  363. }
  364. #endif
  365. }
  366. /// <summary>设置 Updated 属性。</summary>
  367. /// <returns>TRUE:设置成功;FALSE:设置失败。</returns>
  368. public static bool SetUpdated(object record)
  369. {
  370. if (record == null) return false;
  371. var setted = false;
  372. if (record is IRecordMoment moment)
  373. {
  374. moment.Updated = moment.GenerateMoment();
  375. setted = true;
  376. }
  377. if (record is IRecordStamp stamp)
  378. {
  379. stamp.Updated = stamp.GenerateStamp();
  380. setted = true;
  381. }
  382. return setted;
  383. }
  384. /// <summary>枚举带有 Table 特性的 <typeparamref name="T"/> 派生类型。</summary>
  385. public static Type[] EnumerateRecords<T>() where T : IRecord => EnumerateRecords(typeof(T));
  386. /// <summary>枚举带有 Table 特性的派生类型。</summary>
  387. /// <exception cref="ArgumentNullException"></exception>
  388. public static Type[] EnumerateRecords(Type baseType)
  389. {
  390. if (baseType == null) throw new ArgumentNullException(nameof(baseType));
  391. var assemblies = AppDomain.CurrentDomain.GetAssemblies();
  392. var builder = new ArrayBuilder<Type>();
  393. foreach (var assembly in assemblies)
  394. {
  395. var types = RuntimeUtility.GetTypes(assembly);
  396. foreach (var type in types)
  397. {
  398. if (!EnumerateRecords(type, baseType)) continue;
  399. if (builder.Contains(type)) continue;
  400. builder.Add(type);
  401. }
  402. }
  403. return builder.Export();
  404. }
  405. static bool EnumerateRecords(Type type, Type @base)
  406. {
  407. if (type == null || @base == null) return false;
  408. if (type.IsAbstract) return false;
  409. if (!RuntimeUtility.Contains<TableAttribute>(type, false)) return false;
  410. if (type.Equals(@base)) return true;
  411. if (RuntimeUtility.IsInherits(type, @base)) return true;
  412. return false;
  413. }
  414. #endregion
  415. #region Query
  416. /// <summary>简单查询:取结果中第 0 列所有单元格的文本形式,可指定查询后关闭服务器连接,返回结果中不包含无效文本。</summary>
  417. /// <param name="source">数据库客户端。</param>
  418. /// <param name="sql">用于查询的 SQL 语句。</param>
  419. /// <param name="parameters">SQL 参数。</param>
  420. /// <exception cref="SqlException"></exception>
  421. public static string[] Column(this IDbAdo source, string sql, object parameters = null)
  422. {
  423. if (source == null) return new string[0];
  424. var pool = null as string[];
  425. var rows = 0;
  426. var count = 0;
  427. using (var query = source.Query(sql, parameters))
  428. {
  429. if (!query.Success) throw new SqlException(query, sql);
  430. rows = query.Rows;
  431. if (rows < 1) return new string[0];
  432. pool = new string[rows];
  433. for (int i = 0; i < rows; i++)
  434. {
  435. var cell = TextUtility.Trim(query.Text(i, 0));
  436. if (string.IsNullOrEmpty(cell)) continue;
  437. pool[count] = cell;
  438. count++;
  439. }
  440. }
  441. if (count < 1) return new string[0];
  442. if (count == rows) return pool;
  443. var array = new string[count];
  444. Array.Copy(pool, 0, array, 0, count);
  445. return array;
  446. }
  447. /// <summary>简单查询:取结果中第 0 行、第 0 列单元格中的文本,可指定查询后关闭服务器连接。</summary>
  448. /// <param name="dbClient">数据库客户端。</param>
  449. /// <param name="sql">用于查询的 SQL 语句。</param>
  450. /// <param name="parameters">SQL 参数。</param>
  451. /// <exception cref="ArgumentNullException"></exception>
  452. /// <exception cref="SqlException"></exception>
  453. public static string Cell(this IDbAdo dbClient, string sql, object parameters = null)
  454. {
  455. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  456. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  457. using (var query = dbClient.Query(sql, parameters))
  458. {
  459. if (!query.Success) throw new SqlException(query, sql);
  460. var value = TextUtility.Trim(query.Text(0, 0));
  461. return value;
  462. }
  463. }
  464. /// <summary>查询。</summary>
  465. /// <param name="dbClient">数据库连接。</param>
  466. /// <param name="sql">SQL 语句。</param>
  467. /// <param name="parameters">SQL 参数。</param>
  468. /// <exception cref="ArgumentNullException"></exception>
  469. public static IQuery Query(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  470. {
  471. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  472. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  473. var ps = Parameters(dbClient, sql, parameters);
  474. return dbClient.Query(sql, ps);
  475. }
  476. /// <summary>查询。</summary>
  477. /// <param name="dbClient">数据库连接。</param>
  478. /// <param name="sql">SQL 语句。</param>
  479. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  480. /// <exception cref="ArgumentNullException"></exception>
  481. public static IQuery Query(this IDbAdo dbClient, string sql, object parameters = null)
  482. {
  483. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  484. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  485. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  486. {
  487. var ps = Parameters(dbClient, sql, kvps);
  488. return dbClient.Query(sql, ps);
  489. }
  490. else
  491. {
  492. var ps = ParametersByProperites(dbClient, sql, parameters);
  493. return dbClient.Query(sql, ps);
  494. }
  495. }
  496. /// <summary>执行 SELECT 语句,获取查询结果。</summary>
  497. /// <param name="connection">数据库连接。</param>
  498. /// <param name="transaction">事务。</param>
  499. /// <param name="sql">SQL 语句。</param>
  500. /// <param name="parameters">参数。</param>
  501. /// <param name="timeout">超时秒数。</param>
  502. /// <returns>查询结果。</returns>
  503. public static DataTable Query(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  504. {
  505. if (connection == null) throw new ArgumentNullException(nameof(connection));
  506. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  507. if (connection.State != ConnectionState.Open) connection.Open();
  508. using (var command = connection.CreateCommand())
  509. {
  510. if (transaction != null) command.Transaction = transaction;
  511. if (timeout > 0) command.CommandTimeout = timeout;
  512. command.CommandText = sql;
  513. if (parameters != null)
  514. {
  515. foreach (var parameter in parameters)
  516. {
  517. if (parameter == null) continue;
  518. command.Parameters.Add(parameter);
  519. }
  520. }
  521. using (var reader = command.ExecuteReader())
  522. {
  523. var table = new DataTable();
  524. table.Load(reader);
  525. return table;
  526. }
  527. }
  528. }
  529. /// <summary>查询。</summary>
  530. /// <param name="dbClient">数据库连接。</param>
  531. /// <param name="sql">SQL 语句。</param>
  532. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  533. /// <exception cref="ArgumentNullException"></exception>
  534. /// <exception cref="NotImplementedException"></exception>
  535. public static T[] Query<T>(this IDbOrm dbClient, string sql, object parameters = null) where T : class, new()
  536. {
  537. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  538. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  539. if (dbClient is IDbAdo ado)
  540. {
  541. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  542. {
  543. var ps = Parameters(ado, sql, kvps);
  544. return dbClient.Query<T>(sql, ps);
  545. }
  546. else
  547. {
  548. var ps = ParametersByProperites(ado, sql, parameters);
  549. return dbClient.Query<T>(sql, ps);
  550. }
  551. }
  552. else
  553. {
  554. throw new NotImplementedException($"连接未实现 {nameof(IDbAdo)} 接口,无法创建参数。");
  555. }
  556. }
  557. #if !NET20
  558. /// <summary>执行查询,将结果输出为元组数组。</summary>
  559. /// <typeparam name="T">元组中的值类型。</typeparam>
  560. /// <param name="dbClient">数据库连接。</param>
  561. /// <param name="sql">SQL 语句。</param>
  562. /// <param name="parameters">SQL 参数。</param>
  563. /// <param name="getValue">获取第一个值的回调函数。</param>
  564. /// <returns>由元组组成的数组。</returns>
  565. /// <exception cref="ArgumentNullException"></exception>
  566. /// <exception cref="SqlException"></exception>
  567. public static Tuple<T>[] Query<T>(this IDbAdo dbClient, string sql, object parameters, Func<object, T> getValue)
  568. {
  569. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  570. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  571. if (getValue == null) throw new ArgumentNullException(nameof(getValue));
  572. using (var query = dbClient.Query(sql, parameters))
  573. {
  574. if (!query.Success) throw new SqlException(query, sql);
  575. var tuples = new Tuple<T>[query.Rows];
  576. for (var i = 0; i < query.Rows; i++)
  577. {
  578. var value1 = getValue(query.Value(i, 0));
  579. tuples[i] = new Tuple<T>(value1);
  580. }
  581. return tuples;
  582. }
  583. }
  584. /// <summary>执行查询,将结果输出为元组数组。</summary>
  585. /// <param name="dbClient">数据库连接。</param>
  586. /// <param name="sql">SQL 语句。</param>
  587. /// <param name="parameters">SQL 参数。</param>
  588. /// <param name="getValue1">获取第一个值的回调函数。</param>
  589. /// <param name="getValue2">获取第二个值的回调函数。</param>
  590. /// <returns>由元组组成的数组。</returns>
  591. /// <exception cref="ArgumentNullException"></exception>
  592. /// <exception cref="SqlException"></exception>
  593. public static Tuple<T1, T2>[] Query<T1, T2>(this IDbAdo dbClient, string sql, object parameters,
  594. Func<object, T1> getValue1,
  595. Func<object, T2> getValue2)
  596. {
  597. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  598. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  599. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  600. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  601. using (var query = dbClient.Query(sql, parameters))
  602. {
  603. if (!query.Success) throw new SqlException(query, sql);
  604. var tuples = new Tuple<T1, T2>[query.Rows];
  605. for (var i = 0; i < query.Rows; i++)
  606. {
  607. var v1 = getValue1(query.Value(i, 0));
  608. var v2 = getValue2(query.Value(i, 1));
  609. tuples[i] = new Tuple<T1, T2>(v1, v2);
  610. }
  611. return tuples;
  612. }
  613. }
  614. /// <summary>执行查询,将结果输出为元组数组。</summary>
  615. /// <param name="dbClient">数据库连接。</param>
  616. /// <param name="sql">SQL 语句。</param>
  617. /// <param name="parameters">SQL 参数。</param>
  618. /// <param name="getValue1">获取第一个值的回调函数。</param>
  619. /// <param name="getValue2">获取第二个值的回调函数。</param>
  620. /// <param name="getValue3">获取第三个值的回调函数。</param>
  621. /// <returns>由元组组成的数组。</returns>
  622. /// <exception cref="ArgumentNullException"></exception>
  623. /// <exception cref="SqlException"></exception>
  624. public static Tuple<T1, T2, T3>[] Query<T1, T2, T3>(this IDbAdo dbClient, string sql, object parameters,
  625. Func<object, T1> getValue1,
  626. Func<object, T2> getValue2,
  627. Func<object, T3> getValue3)
  628. {
  629. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  630. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  631. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  632. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  633. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  634. using (var query = dbClient.Query(sql, parameters))
  635. {
  636. if (!query.Success) throw new SqlException(query, sql);
  637. var tuples = new Tuple<T1, T2, T3>[query.Rows];
  638. for (var i = 0; i < query.Rows; i++)
  639. {
  640. var v1 = getValue1(query.Value(i, 0));
  641. var v2 = getValue2(query.Value(i, 1));
  642. var v3 = getValue3(query.Value(i, 2));
  643. tuples[i] = new Tuple<T1, T2, T3>(v1, v2, v3);
  644. }
  645. return tuples;
  646. }
  647. }
  648. /// <summary>执行查询,将结果输出为元组数组。</summary>
  649. /// <param name="dbClient">数据库连接。</param>
  650. /// <param name="sql">SQL 语句。</param>
  651. /// <param name="parameters">SQL 参数。</param>
  652. /// <param name="getValue1">获取第一个值的回调函数。</param>
  653. /// <param name="getValue2">获取第二个值的回调函数。</param>
  654. /// <param name="getValue3">获取第三个值的回调函数。</param>
  655. /// <param name="getValue4">获取第四个值的回调函数。</param>
  656. /// <returns>由元组组成的数组。</returns>
  657. /// <exception cref="ArgumentNullException"></exception>
  658. /// <exception cref="SqlException"></exception>
  659. public static Tuple<T1, T2, T3, T4>[] Query<T1, T2, T3, T4>(this IDbAdo dbClient, string sql, object parameters,
  660. Func<object, T1> getValue1,
  661. Func<object, T2> getValue2,
  662. Func<object, T3> getValue3,
  663. Func<object, T4> getValue4)
  664. {
  665. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  666. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  667. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  668. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  669. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  670. if (getValue4 == null) throw new ArgumentNullException(nameof(getValue4));
  671. using (var query = dbClient.Query(sql, parameters))
  672. {
  673. if (!query.Success) throw new SqlException(query, sql);
  674. var tuples = new Tuple<T1, T2, T3, T4>[query.Rows];
  675. for (var i = 0; i < query.Rows; i++)
  676. {
  677. var v1 = getValue1(query.Value(i, 0));
  678. var v2 = getValue2(query.Value(i, 1));
  679. var v3 = getValue3(query.Value(i, 2));
  680. var v4 = getValue4(query.Value(i, 3));
  681. tuples[i] = new Tuple<T1, T2, T3, T4>(v1, v2, v3, v4);
  682. }
  683. return tuples;
  684. }
  685. }
  686. /// <summary>执行查询,将结果输出为元组数组。</summary>
  687. /// <param name="dbClient">数据库连接。</param>
  688. /// <param name="sql">SQL 语句。</param>
  689. /// <param name="parameters">SQL 参数。</param>
  690. /// <param name="getValue1">获取第一个值的回调函数。</param>
  691. /// <param name="getValue2">获取第二个值的回调函数。</param>
  692. /// <param name="getValue3">获取第三个值的回调函数。</param>
  693. /// <param name="getValue4">获取第四个值的回调函数。</param>
  694. /// <param name="getValue5">获取第五个值的回调函数。</param>
  695. /// <returns>由元组组成的数组。</returns>
  696. /// <exception cref="ArgumentNullException"></exception>
  697. /// <exception cref="SqlException"></exception>
  698. public static Tuple<T1, T2, T3, T4, T5>[] Query<T1, T2, T3, T4, T5>(this IDbAdo dbClient, string sql, object parameters,
  699. Func<object, T1> getValue1,
  700. Func<object, T2> getValue2,
  701. Func<object, T3> getValue3,
  702. Func<object, T4> getValue4,
  703. Func<object, T5> getValue5)
  704. {
  705. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  706. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  707. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  708. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  709. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  710. if (getValue4 == null) throw new ArgumentNullException(nameof(getValue4));
  711. if (getValue5 == null) throw new ArgumentNullException(nameof(getValue5));
  712. using (var query = dbClient.Query(sql, parameters))
  713. {
  714. if (!query.Success) throw new SqlException(query, sql);
  715. var tuples = new Tuple<T1, T2, T3, T4, T5>[query.Rows];
  716. for (var i = 0; i < query.Rows; i++)
  717. {
  718. var v1 = getValue1(query.Value(i, 0));
  719. var v2 = getValue2(query.Value(i, 1));
  720. var v3 = getValue3(query.Value(i, 2));
  721. var v4 = getValue4(query.Value(i, 3));
  722. var v5 = getValue5(query.Value(i, 4));
  723. tuples[i] = new Tuple<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
  724. }
  725. return tuples;
  726. }
  727. }
  728. /// <summary>执行查询,将结果输出为元组数组。</summary>
  729. /// <param name="dbClient">数据库连接。</param>
  730. /// <param name="sql">SQL 语句。</param>
  731. /// <param name="parameters">SQL 参数。</param>
  732. /// <param name="getValue1">获取第一个值的回调函数。</param>
  733. /// <param name="getValue2">获取第二个值的回调函数。</param>
  734. /// <param name="getValue3">获取第三个值的回调函数。</param>
  735. /// <param name="getValue4">获取第四个值的回调函数。</param>
  736. /// <param name="getValue5">获取第五个值的回调函数。</param>
  737. /// <param name="getValue6">获取第六个值的回调函数。</param>
  738. /// <returns>由元组组成的数组。</returns>
  739. /// <exception cref="ArgumentNullException"></exception>
  740. /// <exception cref="SqlException"></exception>
  741. public static Tuple<T1, T2, T3, T4, T5, T6>[] Query<T1, T2, T3, T4, T5, T6>(this IDbAdo dbClient, string sql, object parameters,
  742. Func<object, T1> getValue1,
  743. Func<object, T2> getValue2,
  744. Func<object, T3> getValue3,
  745. Func<object, T4> getValue4,
  746. Func<object, T5> getValue5,
  747. Func<object, T6> getValue6)
  748. {
  749. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  750. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  751. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  752. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  753. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  754. if (getValue4 == null) throw new ArgumentNullException(nameof(getValue4));
  755. if (getValue5 == null) throw new ArgumentNullException(nameof(getValue5));
  756. if (getValue6 == null) throw new ArgumentNullException(nameof(getValue6));
  757. using (var query = dbClient.Query(sql, parameters))
  758. {
  759. if (!query.Success) throw new SqlException(query, sql);
  760. var tuples = new Tuple<T1, T2, T3, T4, T5, T6>[query.Rows];
  761. for (var i = 0; i < query.Rows; i++)
  762. {
  763. var v1 = getValue1(query.Value(i, 0));
  764. var v2 = getValue2(query.Value(i, 1));
  765. var v3 = getValue3(query.Value(i, 2));
  766. var v4 = getValue4(query.Value(i, 3));
  767. var v5 = getValue5(query.Value(i, 4));
  768. var v6 = getValue6(query.Value(i, 5));
  769. tuples[i] = new Tuple<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6);
  770. }
  771. return tuples;
  772. }
  773. }
  774. /// <summary>执行查询,将结果输出为元组数组。</summary>
  775. /// <param name="dbClient">数据库连接。</param>
  776. /// <param name="sql">SQL 语句。</param>
  777. /// <param name="parameters">SQL 参数。</param>
  778. /// <param name="getValue1">获取第一个值的回调函数。</param>
  779. /// <param name="getValue2">获取第二个值的回调函数。</param>
  780. /// <param name="getValue3">获取第三个值的回调函数。</param>
  781. /// <param name="getValue4">获取第四个值的回调函数。</param>
  782. /// <param name="getValue5">获取第五个值的回调函数。</param>
  783. /// <param name="getValue6">获取第六个值的回调函数。</param>
  784. /// <param name="getValue7">获取第七个值的回调函数。</param>
  785. /// <returns>由元组组成的数组。</returns>
  786. /// <exception cref="ArgumentNullException"></exception>
  787. /// <exception cref="SqlException"></exception>
  788. public static Tuple<T1, T2, T3, T4, T5, T6, T7>[] Query<T1, T2, T3, T4, T5, T6, T7>(this IDbAdo dbClient, string sql, object parameters,
  789. Func<object, T1> getValue1,
  790. Func<object, T2> getValue2,
  791. Func<object, T3> getValue3,
  792. Func<object, T4> getValue4,
  793. Func<object, T5> getValue5,
  794. Func<object, T6> getValue6,
  795. Func<object, T7> getValue7)
  796. {
  797. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  798. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  799. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  800. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  801. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  802. if (getValue4 == null) throw new ArgumentNullException(nameof(getValue4));
  803. if (getValue5 == null) throw new ArgumentNullException(nameof(getValue5));
  804. if (getValue6 == null) throw new ArgumentNullException(nameof(getValue6));
  805. if (getValue7 == null) throw new ArgumentNullException(nameof(getValue7));
  806. using (var query = dbClient.Query(sql, parameters))
  807. {
  808. if (!query.Success) throw new SqlException(query, sql);
  809. var tuples = new Tuple<T1, T2, T3, T4, T5, T6, T7>[query.Rows];
  810. for (var i = 0; i < query.Rows; i++)
  811. {
  812. var v1 = getValue1(query.Value(i, 0));
  813. var v2 = getValue2(query.Value(i, 1));
  814. var v3 = getValue3(query.Value(i, 2));
  815. var v4 = getValue4(query.Value(i, 3));
  816. var v5 = getValue5(query.Value(i, 4));
  817. var v6 = getValue6(query.Value(i, 5));
  818. var v7 = getValue7(query.Value(i, 6));
  819. tuples[i] = new Tuple<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5, v6, v7);
  820. }
  821. return tuples;
  822. }
  823. }
  824. /// <summary>执行查询,将结果输出为元组数组。</summary>
  825. /// <param name="dbClient">数据库连接。</param>
  826. /// <param name="sql">SQL 语句。</param>
  827. /// <param name="parameters">SQL 参数。</param>
  828. /// <param name="getValue1">获取第一个值的回调函数。</param>
  829. /// <param name="getValue2">获取第二个值的回调函数。</param>
  830. /// <param name="getValue3">获取第三个值的回调函数。</param>
  831. /// <param name="getValue4">获取第四个值的回调函数。</param>
  832. /// <param name="getValue5">获取第五个值的回调函数。</param>
  833. /// <param name="getValue6">获取第六个值的回调函数。</param>
  834. /// <param name="getValue7">获取第七个值的回调函数。</param>
  835. /// <param name="getValue8">获取第八个值的回调函数。</param>
  836. /// <returns>由元组组成的数组。</returns>
  837. /// <exception cref="ArgumentNullException"></exception>
  838. /// <exception cref="SqlException"></exception>
  839. public static Tuple<T1, T2, T3, T4, T5, T6, T7, T8>[] Query<T1, T2, T3, T4, T5, T6, T7, T8>(this IDbAdo dbClient, string sql, object parameters,
  840. Func<object, T1> getValue1,
  841. Func<object, T2> getValue2,
  842. Func<object, T3> getValue3,
  843. Func<object, T4> getValue4,
  844. Func<object, T5> getValue5,
  845. Func<object, T6> getValue6,
  846. Func<object, T7> getValue7,
  847. Func<object, T8> getValue8)
  848. {
  849. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  850. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  851. if (getValue1 == null) throw new ArgumentNullException(nameof(getValue1));
  852. if (getValue2 == null) throw new ArgumentNullException(nameof(getValue2));
  853. if (getValue3 == null) throw new ArgumentNullException(nameof(getValue3));
  854. if (getValue4 == null) throw new ArgumentNullException(nameof(getValue4));
  855. if (getValue5 == null) throw new ArgumentNullException(nameof(getValue5));
  856. if (getValue6 == null) throw new ArgumentNullException(nameof(getValue6));
  857. if (getValue7 == null) throw new ArgumentNullException(nameof(getValue7));
  858. if (getValue8 == null) throw new ArgumentNullException(nameof(getValue8));
  859. using (var query = dbClient.Query(sql, parameters))
  860. {
  861. if (!query.Success) throw new SqlException(query, sql);
  862. var tuples = new Tuple<T1, T2, T3, T4, T5, T6, T7, T8>[query.Rows];
  863. for (var i = 0; i < query.Rows; i++)
  864. {
  865. var v1 = getValue1(query.Value(i, 0));
  866. var v2 = getValue2(query.Value(i, 1));
  867. var v3 = getValue3(query.Value(i, 2));
  868. var v4 = getValue4(query.Value(i, 3));
  869. var v5 = getValue5(query.Value(i, 4));
  870. var v6 = getValue6(query.Value(i, 5));
  871. var v7 = getValue7(query.Value(i, 6));
  872. var v8 = getValue8(query.Value(i, 7));
  873. tuples[i] = new Tuple<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4, v5, v6, v7, v8);
  874. }
  875. return tuples;
  876. }
  877. }
  878. #endif
  879. #endregion
  880. #region Execute
  881. /// <summary>执行 SQL 语句,并加入参数。</summary>
  882. /// <exception cref="ArgumentNullException"></exception>
  883. public static IExecute Execute(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters, bool autoTransaction = false)
  884. {
  885. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  886. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  887. var ps = Parameters(dbClient, sql, parameters);
  888. return dbClient.Execute(sql, ps, autoTransaction);
  889. }
  890. /// <summary>执行 SQL 语句,并加入参数。</summary>
  891. /// <param name="dbClient">数据库连接。</param>
  892. /// <param name="sql">SQL 语句。</param>
  893. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  894. /// <param name="autoTransaction">自动使用事务。</param>
  895. /// <exception cref="ArgumentNullException"></exception>
  896. public static IExecute Execute(this IDbAdo dbClient, string sql, object parameters = null, bool autoTransaction = false)
  897. {
  898. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  899. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  900. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  901. {
  902. var ps = Parameters(dbClient, sql, kvps);
  903. return dbClient.Execute(sql, ps, autoTransaction);
  904. }
  905. {
  906. var ps = ParametersByProperites(dbClient, sql, parameters);
  907. return dbClient.Execute(sql, ps, autoTransaction);
  908. }
  909. }
  910. /// <summary>执行 SQL 语句,获取影响的行数。</summary>
  911. /// <param name="connection">数据库连接。</param>
  912. /// <param name="transaction">事务。</param>
  913. /// <param name="sql">SQL 语句。</param>
  914. /// <param name="parameters">参数。</param>
  915. /// <param name="timeout">超时秒数。</param>
  916. /// <returns>行数。</returns>
  917. public static int Execute(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  918. {
  919. if (connection == null) throw new ArgumentNullException(nameof(connection));
  920. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  921. if (connection.State != ConnectionState.Open) connection.Open();
  922. using (var command = connection.CreateCommand())
  923. {
  924. if (transaction != null) command.Transaction = transaction;
  925. if (timeout > 0) command.CommandTimeout = timeout;
  926. command.CommandText = sql;
  927. if (parameters != null)
  928. {
  929. foreach (var parameter in parameters)
  930. {
  931. if (parameter == null) continue;
  932. command.Parameters.Add(parameter);
  933. }
  934. }
  935. var rows = command.ExecuteNonQuery();
  936. return rows;
  937. }
  938. }
  939. #endregion
  940. #region Transaction
  941. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  942. /// <exception cref="ArgumentNullException"></exception>
  943. /// <exception cref="SqlException"></exception>
  944. public static void InTransaction(this IDbAdo source, Action action)
  945. {
  946. // 检查参数。
  947. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  948. if (action == null) throw new ArgumentNullException(nameof(action), "没有指定要在事物中执行的程序。");
  949. InTransaction<object>(source, () =>
  950. {
  951. action.Invoke();
  952. return null;
  953. });
  954. }
  955. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  956. /// <exception cref="ArgumentNullException"></exception>
  957. /// <exception cref="SqlException"></exception>
  958. public static T InTransaction<T>(this IDbAdo source, Func<T> func)
  959. {
  960. // 检查参数。
  961. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  962. if (func == null) throw new ArgumentNullException(nameof(func), "没有指定要在事物中执行的程序。");
  963. // 已经存在事务。
  964. if (source.Transaction != null) return func.Invoke();
  965. // 启动事务。
  966. var begin = source.Begin();
  967. if (begin.NotEmpty()) throw new SqlException("无法启动事务:" + begin);
  968. var result = default(T);
  969. var success = false;
  970. try
  971. {
  972. // 在事务内运行。
  973. result = func.Invoke();
  974. success = true;
  975. }
  976. finally
  977. {
  978. if (success)
  979. {
  980. // 执行成功,提交事务。
  981. var commit = source.Commit();
  982. if (!string.IsNullOrEmpty(commit)) throw new SqlException(commit);
  983. }
  984. else
  985. {
  986. // 执行失败,回滚事务。
  987. try { source.Rollback(); } catch { }
  988. }
  989. }
  990. return result;
  991. }
  992. #endregion
  993. #region Parameter
  994. /// <exception cref="ArgumentNullException"></exception>
  995. static List<IDataParameter> ParametersByProperites(IDbAdo dbClient, string sql, object parameters)
  996. {
  997. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  998. if (parameters == null) return null;
  999. var lsql = sql.Lower();
  1000. var type = parameters.GetType();
  1001. var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  1002. var count = properties.Length;
  1003. var dict = new Dictionary<string, object>(count);
  1004. for (var i = 0; i < count; i++)
  1005. {
  1006. var property = properties[i];
  1007. // 属性必须能够获取值。
  1008. var getter = property.GetGetMethod();
  1009. if (getter == null) continue;
  1010. // 属性值必须有效。
  1011. var name = property.Name;
  1012. if (name.IsEmpty()) continue;
  1013. // 属性不可重复。
  1014. if (!name.StartsWith("@")) name = "@" + name;
  1015. if (dict.ContainsKey(name)) continue;
  1016. // SQL 语句中必须包含此参数。
  1017. var lname = name.Lower();
  1018. if (!lsql.Contains(lname)) continue;
  1019. // 加入字典。
  1020. var value = getter.Invoke(parameters, null);
  1021. dict.Add(name, value);
  1022. }
  1023. if (dict.Count < 1) return null;
  1024. var ps = new List<IDataParameter>();
  1025. foreach (var kvp in dict)
  1026. {
  1027. var p = dbClient.Parameter(kvp.Key, kvp.Value);
  1028. ps.Add(p);
  1029. }
  1030. return ps;
  1031. }
  1032. /// <exception cref="ArgumentNullException"></exception>
  1033. static List<IDataParameter> Parameters(IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  1034. {
  1035. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  1036. if (parameters == null) return null;
  1037. var lsql = sql.Lower();
  1038. var names = new List<string>(20);
  1039. var ps = new List<IDataParameter>(20);
  1040. foreach (var kvp in parameters)
  1041. {
  1042. var name = kvp.Key;
  1043. if (name.IsEmpty()) continue;
  1044. // 属性不可重复。
  1045. if (!name.StartsWith("@")) name = "@" + name;
  1046. if (names.Contains(name)) continue;
  1047. // SQL 语句中必须包含此参数。
  1048. var lname = name.Lower();
  1049. if (!lsql.Contains(lname)) continue;
  1050. var p = dbClient.Parameter(name, kvp.Value);
  1051. ps.Add(p);
  1052. names.Add(name);
  1053. }
  1054. return ps;
  1055. }
  1056. #endregion
  1057. #region SQL
  1058. /// <summary>对文本转义,符合 SQL 安全性。可根据字段类型限制 UTF-8 字节数,默认为 0 时不限制字节数。</summary>
  1059. public static string Escape(this string text, int bytes = 0)
  1060. {
  1061. if (text.IsEmpty()) return "";
  1062. var t = text ?? "";
  1063. t = t.Replace("\\", "\\\\");
  1064. t = t.Replace("'", "\\'");
  1065. t = t.Replace("\n", "\\n");
  1066. t = t.Replace("\r", "\\r");
  1067. t = t.Replace("\b", "\\b");
  1068. t = t.Replace("\t", "\\t");
  1069. t = t.Replace("\f", "\\f");
  1070. if (bytes > 5)
  1071. {
  1072. if (t.Bytes(Encoding.UTF8).Length > bytes)
  1073. {
  1074. while (true)
  1075. {
  1076. t = t.Substring(0, t.Length - 1);
  1077. if (t.Bytes(Encoding.UTF8).Length <= (bytes - 4)) break;
  1078. }
  1079. t = t + " ...";
  1080. }
  1081. }
  1082. return t;
  1083. }
  1084. /// <summary>限定名称文本,只允许包含字母、数字和下划线。</summary>
  1085. public static string SafeName(this string name) => TextUtility.Restrict(name, "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  1086. #endregion
  1087. #region 数据模型 -> DataTable
  1088. /// <summary>将多个实体元素转换为 DataTable。</summary>
  1089. /// <typeparam name="T">实体元素的类型。</typeparam>
  1090. /// <param name="items">实体元素。</param>
  1091. /// <param name="tableName">设置 <see cref="DataTable"/> 的名称。</param>
  1092. /// <exception cref="ArgumentNullException"></exception>
  1093. /// <exception cref="DuplicateNameException"></exception>
  1094. /// <exception cref="InvalidExpressionException"></exception>
  1095. public static DataTable DataTable<T>(this IEnumerable<T> items, string tableName = null)
  1096. {
  1097. if (items == null) throw new ArgumentNullException(nameof(items));
  1098. // 解析表结构。
  1099. var it = typeof(T);
  1100. var ts = TableStructure.Parse(it, true, true);
  1101. if (ts == null || ts.Columns == null || ts.Columns.Length < 1)
  1102. {
  1103. foreach (var item in items)
  1104. {
  1105. if (item == null) continue;
  1106. var itemType = item.GetType();
  1107. ts = TableStructure.Parse(itemType, true, true);
  1108. if (ts == null) throw new TypeLoadException($"无法解析 {itemType.FullName} 的结构。");
  1109. it = itemType;
  1110. break;
  1111. }
  1112. if (ts == null) throw new TypeLoadException($"无法解析 {it.FullName} 的结构。");
  1113. }
  1114. var cas = ts.Columns;
  1115. var width = cas.Length;
  1116. if (width < 1) throw new TypeLoadException($"类型 {it.FullName} 的结构中没有列。");
  1117. // 初始化列。
  1118. var table = new DataTable();
  1119. var pis = new PropertyInfo[width];
  1120. var fts = new Type[width];
  1121. for (var i = 0; i < width; i++)
  1122. {
  1123. var ca = cas[i];
  1124. var pi = ca.Property;
  1125. var pt = pi.PropertyType;
  1126. pis[i] = pi;
  1127. var ft = pt;
  1128. if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
  1129. {
  1130. pt.GetGenericArguments();
  1131. ft = Nullable.GetUnderlyingType(pt);
  1132. }
  1133. fts[i] = ft;
  1134. var column = new DataColumn(ca.Field, ft);
  1135. column.AllowDBNull = true;
  1136. table.Columns.Add(column);
  1137. }
  1138. // 添加行。
  1139. foreach (var item in items)
  1140. {
  1141. if (item == null) continue;
  1142. var values = new ArrayBuilder<object>(width);
  1143. for (var i = 0; i < width; i++)
  1144. {
  1145. var value = pis[i].GetValue(item, null);
  1146. if (value is DateTime dt)
  1147. {
  1148. if (dt.Year < 1753)
  1149. {
  1150. values.Add(DBNull.Value);
  1151. continue;
  1152. }
  1153. }
  1154. values.Add(value);
  1155. }
  1156. table.Rows.Add(values.Export());
  1157. }
  1158. if (tableName.NotEmpty()) table.TableName = tableName;
  1159. else if (ts.TableName.NotEmpty()) table.TableName = ts.TableName;
  1160. return table;
  1161. }
  1162. #endregion
  1163. #region DataTable 序列化
  1164. /// <summary>转换 <see cref="System.Data.DataTable"/> 到 <see cref="ObjectSet{T}"/> 数组,每行记录为一个 ObjectSet 对象。</summary>
  1165. /// <returns>当参数 table 无效时返回 0 长度的 <see cref="ObjectSet{T}"/> 数组。</returns>
  1166. public static ObjectSet[] ObjectSet(this DataTable table)
  1167. {
  1168. if (table == null) return new ObjectSet[0];
  1169. var columns = table.Columns.Count;
  1170. var fields = new string[columns];
  1171. for (var c = 0; c < columns; c++) fields[c] = table.Columns[c].ColumnName;
  1172. var rows = table.Rows.Count;
  1173. var dicts = new Dictionary<string, object>[rows];
  1174. for (var r = 0; r < table.Rows.Count; r++)
  1175. {
  1176. var dict = new Dictionary<string, object>(columns);
  1177. for (var c = 0; c < columns; c++)
  1178. {
  1179. var field = fields[c];
  1180. if (string.IsNullOrEmpty(field)) continue;
  1181. if (dict.ContainsKey(field)) continue;
  1182. var v = table.Rows[r][c];
  1183. if (v.IsNull()) v = null;
  1184. dict.Add(field, v);
  1185. }
  1186. dicts[r] = dict;
  1187. }
  1188. var oss = new ObjectSet[rows];
  1189. for (var i = 0; i < rows; i++) oss[i] = new ObjectSet(dicts[i]);
  1190. return oss;
  1191. }
  1192. /// <summary>转换为 Json 对象。</summary>
  1193. public static Json ToJson(this DataTable table, Func<DateTime, string> dateTimeFormatter = null)
  1194. {
  1195. if (table == null) return null;
  1196. var columns = ToJson(table.Columns);
  1197. var rows = ToJson(table.Rows, dateTimeFormatter);
  1198. var jsonObject = Json.NewObject();
  1199. jsonObject.SetProperty("columns", columns);
  1200. jsonObject.SetProperty("rows", rows);
  1201. return jsonObject;
  1202. }
  1203. /// <summary>转换为 Json 对象。</summary>
  1204. public static Json ToJson(this DataColumnCollection columns)
  1205. {
  1206. if (columns == null) return null;
  1207. var json = Json.NewArray();
  1208. var count = columns.Count;
  1209. for (var c = 0; c < count; c++)
  1210. {
  1211. var dc = columns[c];
  1212. var column = Json.NewObject();
  1213. column.SetProperty("name", dc.ColumnName);
  1214. column.SetProperty("type", dc.DataType.FullName);
  1215. json.AddItem(column);
  1216. }
  1217. return json;
  1218. }
  1219. /// <summary>转换为 Json 对象。</summary>
  1220. public static Json ToJson(this DataRowCollection rows, Func<DateTime, object> dateTimeFormatter = null)
  1221. {
  1222. if (rows == null) return null;
  1223. var json = Json.NewArray();
  1224. var count = rows.Count;
  1225. for (var r = 0; r < count; r++)
  1226. {
  1227. json.AddItem(ToJson(rows[r], dateTimeFormatter));
  1228. }
  1229. return json;
  1230. }
  1231. /// <summary>转换为 Json 对象。</summary>
  1232. public static Json ToJson(this DataRow row, Func<DateTime, object> dateTimeFormatter = null)
  1233. {
  1234. if (row == null) return null;
  1235. var cells = row.ItemArray;
  1236. var count = cells.Length;
  1237. var json = Json.NewArray();
  1238. for (var c = 0; c < count; c++)
  1239. {
  1240. var value = cells[c];
  1241. if (value == null || value.Equals(DBNull.Value))
  1242. {
  1243. json.AddItem();
  1244. continue;
  1245. }
  1246. if (value is DateTime vDateTime)
  1247. {
  1248. if (dateTimeFormatter == null)
  1249. {
  1250. json.AddItem(Json.SerializeDateTime(vDateTime));
  1251. continue;
  1252. }
  1253. else
  1254. {
  1255. value = dateTimeFormatter.Invoke(vDateTime);
  1256. if (value == null || value.Equals(DBNull.Value))
  1257. {
  1258. json.AddItem();
  1259. continue;
  1260. }
  1261. }
  1262. }
  1263. if (value is string @string) json.AddItem(@string);
  1264. else if (value is byte @byte) json.AddItem(@byte);
  1265. else if (value is short @short) json.AddItem(@short);
  1266. else if (value is int @int) json.AddItem(@int);
  1267. else if (value is long @long) json.AddItem(@long);
  1268. else if (value is float @float) json.AddItem(@float);
  1269. else if (value is double @double) json.AddItem(@double);
  1270. else if (value is decimal @decimal) json.AddItem(@decimal);
  1271. else if (value is bool @bool) json.AddItem(@bool);
  1272. else if (value is byte[] bytes) json.AddItem(bytes.Base64());
  1273. else json.AddItem(TextUtility.Text(value));
  1274. }
  1275. return json;
  1276. }
  1277. /// <summary>转换 <see cref="DataTable"/> 为 CSV 文本,不存在表时返回 NULL 值。可指定是否包含表头。</summary>
  1278. public static string Csv(DataTable table, bool withHead = false)
  1279. {
  1280. if (table == null) return null;
  1281. var columns = table.Columns.Count;
  1282. if (columns < 1) return "";
  1283. var sb = new StringBuilder();
  1284. if (withHead)
  1285. {
  1286. for (var c = 0; c < columns; c++)
  1287. {
  1288. var v = table.Columns[c].ColumnName;
  1289. CsvCell(sb, c, v);
  1290. }
  1291. }
  1292. var rows = table.Rows.Count;
  1293. for (var r = 0; r < rows; r++)
  1294. {
  1295. var row = table.Rows[r];
  1296. if (withHead || r > 0) sb.Append("\r\n");
  1297. for (var c = 0; c < columns; c++) CsvCell(sb, c, row[c]);
  1298. }
  1299. return sb.ToString();
  1300. }
  1301. private static void CsvCell(StringBuilder sb, int c, object v)
  1302. {
  1303. if (c > 0) sb.Append(",");
  1304. if (v == null || v.Equals(DBNull.Value)) return;
  1305. if (v is bool @bool)
  1306. {
  1307. sb.Append(@bool ? "TRUE" : "FALSE");
  1308. return;
  1309. }
  1310. if (v is DateTime @datetime)
  1311. {
  1312. sb.Append(@datetime.Lucid());
  1313. return;
  1314. }
  1315. 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)
  1316. {
  1317. sb.Append(v.ToString());
  1318. return;
  1319. }
  1320. if (v is char)
  1321. {
  1322. sb.Append((char)v);
  1323. return;
  1324. }
  1325. var s = (v is string @string) ? @string : v.ToString();
  1326. var length = s.Length;
  1327. if (length < 1) return;
  1328. var quote = false;
  1329. var comma = false;
  1330. var newline = false;
  1331. for (var i = 0; i < length; i++)
  1332. {
  1333. var @char = s[i];
  1334. if (@char == '\"') quote = true;
  1335. else if (@char == ',') comma = true;
  1336. else if (@char == '\r') newline = false;
  1337. else if (@char == '\n') newline = false;
  1338. }
  1339. if (quote || comma || newline)
  1340. {
  1341. sb.Append("\"");
  1342. s = s.Replace("\"", "\"\"");
  1343. sb.Append(s);
  1344. sb.Append("\"");
  1345. }
  1346. else sb.Append(s);
  1347. }
  1348. #endregion
  1349. #region DataTable 快捷操作
  1350. /// <summary>获取默认表中指定单元格的内容。</summary>
  1351. /// <param name="table">数据表。</param>
  1352. /// <param name="rowIndex">行索引,从 0 开始。</param>
  1353. /// <param name="columnIndex">列索引,从 0 开始。</param>
  1354. public static object Value(this DataTable table, int rowIndex, int columnIndex)
  1355. {
  1356. if (table != null)
  1357. {
  1358. if (rowIndex >= 0 && rowIndex < table.Rows.Count)
  1359. {
  1360. if (columnIndex >= 0 && columnIndex < table.Columns.Count)
  1361. {
  1362. var value = table.Rows[rowIndex][columnIndex];
  1363. if (value == null || value.Equals(DBNull.Value)) return null;
  1364. return value;
  1365. }
  1366. }
  1367. }
  1368. return null;
  1369. }
  1370. /// <summary>获取默认表中指定单元的内容。</summary>
  1371. /// <param name="table">数据表。</param>
  1372. /// <param name="rowIndex">行索引,从 0 开始。</param>
  1373. /// <param name="columnName">列名称/字段名称,此名称不区分大小写。</param>
  1374. public static object Value(this DataTable table, int rowIndex, string columnName)
  1375. {
  1376. if (table != null && !string.IsNullOrEmpty(columnName))
  1377. {
  1378. if ((rowIndex < table.Rows.Count) && (rowIndex >= 0))
  1379. {
  1380. try
  1381. {
  1382. var value = table.Rows[rowIndex][columnName];
  1383. if (value == null || value.Equals(DBNull.Value)) return null;
  1384. return value;
  1385. }
  1386. catch { }
  1387. }
  1388. }
  1389. return null;
  1390. }
  1391. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1392. public static Class<DateTime> DateTime(this DataTable table, int row, int column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  1393. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1394. public static Class<DateTime> DateTime(this DataTable table, int row, string column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  1395. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1396. public static Int32 Int32(this DataTable table, int row, int column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  1397. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1398. public static Int32 Int32(this DataTable table, int row, string column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  1399. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1400. public static Int64 Int64(this DataTable table, int row, int column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  1401. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1402. public static Int64 Int64(this DataTable table, int row, string column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  1403. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1404. public static Decimal Decimal(this DataTable table, int row, int column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  1405. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1406. public static Decimal Decimal(this DataTable table, int row, string column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  1407. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>>
  1408. public static Double Double(this DataTable table, int row, int column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  1409. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>>
  1410. public static Double Double(this DataTable table, int row, string column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  1411. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  1412. public static string Text(this DataTable table, int row, int column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  1413. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  1414. public static string Text(this DataTable table, int row, string column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  1415. #endregion
  1416. #region Dynamic
  1417. #if NET40_OR_GREATER
  1418. /// <summary>转换 ObjectSet 数组为 dynamic 数组。</summary>
  1419. public static dynamic[] Dynamic(this ObjectSet[] oss)
  1420. {
  1421. if (oss == null) return new dynamic[0];
  1422. var eos = oss.Expando();
  1423. var ds = new dynamic[eos.Length];
  1424. eos.CopyTo(ds, 0);
  1425. return ds;
  1426. }
  1427. #endif
  1428. #endregion
  1429. #region 表达式计算
  1430. /// <summary>计算文本表达式。</summary>
  1431. public static object Compute(string expression)
  1432. {
  1433. using (var table = new DataTable())
  1434. {
  1435. var result = table.Compute(expression, null);
  1436. if (result.IsNull()) return null;
  1437. return result;
  1438. }
  1439. }
  1440. #endregion
  1441. }
  1442. }