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.

1170 lines
50 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
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
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
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
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. /// <exception cref="SqlException"></exception>
  351. public static string[] Column(this IDbAdo source, string sql)
  352. {
  353. if (source == null) return new string[0];
  354. var pool = null as string[];
  355. var rows = 0;
  356. var count = 0;
  357. using (var query = source.Query(sql))
  358. {
  359. if (!query.Success) throw new SqlException(query, sql);
  360. rows = query.Rows;
  361. if (rows < 1) return new string[0];
  362. pool = new string[rows];
  363. for (int i = 0; i < rows; i++)
  364. {
  365. var cell = TextUtility.Trim(query.Text(i, 0));
  366. if (string.IsNullOrEmpty(cell)) continue;
  367. pool[count] = cell;
  368. count++;
  369. }
  370. }
  371. if (count < 1) return new string[0];
  372. if (count == rows) return pool;
  373. var array = new string[count];
  374. Array.Copy(pool, 0, array, 0, count);
  375. return array;
  376. }
  377. /// <summary>简单查询:取结果中第 0 行、第 0 列单元格中的文本,可指定查询后关闭服务器连接。</summary>
  378. /// <param name="dbClient">数据库客户端。</param>
  379. /// <param name="sql">用于查询的 SQL 语句。</param>
  380. /// <exception cref="ArgumentNullException"></exception>
  381. /// <exception cref="SqlException"></exception>
  382. public static string Cell(this IDbAdo dbClient, string sql)
  383. {
  384. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  385. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  386. using (var query = dbClient.Query(sql))
  387. {
  388. if (!query.Success) throw new SqlException(query, sql);
  389. var value = TextUtility.Trim(query.Text(0, 0));
  390. return value;
  391. }
  392. }
  393. /// <summary>查询。</summary>
  394. /// <param name="dbClient">数据库连接。</param>
  395. /// <param name="sql">SQL 语句。</param>
  396. /// <param name="parameters">SQL 参数。</param>
  397. /// <exception cref="ArgumentNullException"></exception>
  398. public static IQuery Query(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  399. {
  400. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  401. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  402. var ps = Parameters(dbClient, sql, parameters);
  403. return dbClient.Query(sql, ps);
  404. }
  405. /// <summary>查询。</summary>
  406. /// <param name="dbClient">数据库连接。</param>
  407. /// <param name="sql">SQL 语句。</param>
  408. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  409. /// <exception cref="ArgumentNullException"></exception>
  410. public static IQuery Query(this IDbAdo dbClient, string sql, object parameters = null)
  411. {
  412. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  413. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  414. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  415. {
  416. var ps = Parameters(dbClient, sql, kvps);
  417. return dbClient.Query(sql, ps);
  418. }
  419. {
  420. var ps = ParametersByProperites(dbClient, sql, parameters);
  421. return dbClient.Query(sql, ps);
  422. }
  423. }
  424. /// <summary>执行 SELECT 语句,获取查询结果。</summary>
  425. /// <param name="connection">数据库连接。</param>
  426. /// <param name="transaction">事务。</param>
  427. /// <param name="sql">SQL 语句。</param>
  428. /// <param name="parameters">参数。</param>
  429. /// <param name="timeout">超时秒数。</param>
  430. /// <returns>查询结果。</returns>
  431. public static DataTable Query(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  432. {
  433. if (connection == null) throw new ArgumentNullException(nameof(connection));
  434. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  435. if (connection.State != ConnectionState.Open) connection.Open();
  436. using (var command = connection.CreateCommand())
  437. {
  438. if (transaction != null) command.Transaction = transaction;
  439. if (timeout > 0) command.CommandTimeout = timeout;
  440. command.CommandText = sql;
  441. if (parameters != null)
  442. {
  443. foreach (var parameter in parameters)
  444. {
  445. if (parameter == null) continue;
  446. command.Parameters.Add(parameter);
  447. }
  448. }
  449. using (var reader = command.ExecuteReader())
  450. {
  451. var table = new DataTable();
  452. table.Load(reader);
  453. return table;
  454. }
  455. }
  456. }
  457. #endregion
  458. #region Execute
  459. /// <summary>执行 SQL 语句,并加入参数。</summary>
  460. /// <exception cref="ArgumentNullException"></exception>
  461. public static IExecute Execute(this IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters, bool autoTransaction = false)
  462. {
  463. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  464. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  465. var ps = Parameters(dbClient, sql, parameters);
  466. return dbClient.Execute(sql, ps, autoTransaction);
  467. }
  468. /// <summary>执行 SQL 语句,并加入参数。</summary>
  469. /// <param name="dbClient">数据库连接。</param>
  470. /// <param name="sql">SQL 语句。</param>
  471. /// <param name="parameters">参数容器,每个属性表示一个 SQL 参数。此方法将会自动补足参数名称的 @ 前缀。</param>
  472. /// <param name="autoTransaction">自动使用事务。</param>
  473. /// <exception cref="ArgumentNullException"></exception>
  474. public static IExecute Execute(this IDbAdo dbClient, string sql, object parameters = null, bool autoTransaction = false)
  475. {
  476. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  477. if (sql.IsEmpty()) throw new ArgumentNullException(nameof(sql));
  478. if (parameters is IEnumerable<KeyValuePair<string, object>> kvps)
  479. {
  480. var ps = Parameters(dbClient, sql, kvps);
  481. return dbClient.Execute(sql, ps, autoTransaction);
  482. }
  483. {
  484. var ps = ParametersByProperites(dbClient, sql, parameters);
  485. return dbClient.Execute(sql, ps, autoTransaction);
  486. }
  487. }
  488. /// <summary>执行 SQL 语句,获取影响的行数。</summary>
  489. /// <param name="connection">数据库连接。</param>
  490. /// <param name="transaction">事务。</param>
  491. /// <param name="sql">SQL 语句。</param>
  492. /// <param name="parameters">参数。</param>
  493. /// <param name="timeout">超时秒数。</param>
  494. /// <returns>行数。</returns>
  495. public static int Execute(this IDbConnection connection, IDbTransaction transaction, string sql, IEnumerable<IDbDataParameter> parameters = null, int timeout = 3600)
  496. {
  497. if (connection == null) throw new ArgumentNullException(nameof(connection));
  498. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
  499. if (connection.State != ConnectionState.Open) connection.Open();
  500. using (var command = connection.CreateCommand())
  501. {
  502. if (transaction != null) command.Transaction = transaction;
  503. if (timeout > 0) command.CommandTimeout = timeout;
  504. command.CommandText = sql;
  505. if (parameters != null)
  506. {
  507. foreach (var parameter in parameters)
  508. {
  509. if (parameter == null) continue;
  510. command.Parameters.Add(parameter);
  511. }
  512. }
  513. var rows = command.ExecuteNonQuery();
  514. return rows;
  515. }
  516. }
  517. #endregion
  518. #region Transaction
  519. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  520. /// <exception cref="ArgumentNullException"></exception>
  521. /// <exception cref="SqlException"></exception>
  522. public static void InTransaction<T>(this IDbAdo source, Action action)
  523. {
  524. // 检查参数。
  525. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  526. if (action == null) throw new ArgumentNullException(nameof(action), "没有指定要执行的过程。");
  527. // 启动事务。
  528. var begin = source.Begin();
  529. if (begin.NotEmpty()) throw new SqlException("无法启动事务:" + begin);
  530. try
  531. {
  532. // 在事务内运行。
  533. action.Invoke();
  534. // 执行成功,提交事务。
  535. var commit = source.Commit();
  536. if (!string.IsNullOrEmpty(commit)) throw new SqlException(commit);
  537. }
  538. catch (Exception ex)
  539. {
  540. // 执行失败,回滚事务。
  541. try { source.Rollback(); } catch { }
  542. throw ex;
  543. }
  544. }
  545. #endregion
  546. #region Parameter
  547. /// <exception cref="ArgumentNullException"></exception>
  548. static List<IDataParameter> ParametersByProperites(IDbAdo dbClient, string sql, object parameters)
  549. {
  550. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  551. if (parameters == null) return null;
  552. var lsql = sql.Lower();
  553. var type = parameters.GetType();
  554. var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  555. var count = properties.Length;
  556. var dict = new Dictionary<string, object>(count);
  557. for (var i = 0; i < count; i++)
  558. {
  559. var property = properties[i];
  560. // 属性必须能够获取值。
  561. var getter = property.GetGetMethod();
  562. if (getter == null) continue;
  563. // 属性值必须有效。
  564. var name = property.Name;
  565. if (name.IsEmpty()) continue;
  566. // 属性不可重复。
  567. if (!name.StartsWith("@")) name = "@" + name;
  568. if (dict.ContainsKey(name)) continue;
  569. // SQL 语句中必须包含此参数。
  570. var lname = name.Lower();
  571. if (!lsql.Contains(lname)) continue;
  572. // 加入字典。
  573. var value = getter.Invoke(parameters, null);
  574. dict.Add(name, value);
  575. }
  576. if (dict.Count < 1) return null;
  577. var ps = new List<IDataParameter>();
  578. foreach (var kvp in dict)
  579. {
  580. var p = dbClient.Parameter(kvp.Key, kvp.Value);
  581. ps.Add(p);
  582. }
  583. return ps;
  584. }
  585. /// <exception cref="ArgumentNullException"></exception>
  586. static List<IDataParameter> Parameters(IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  587. {
  588. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  589. if (parameters == null) return null;
  590. var lsql = sql.Lower();
  591. var names = new List<string>(20);
  592. var ps = new List<IDataParameter>(20);
  593. foreach (var kvp in parameters)
  594. {
  595. var name = kvp.Key;
  596. if (name.IsEmpty()) continue;
  597. // 属性不可重复。
  598. if (!name.StartsWith("@")) name = "@" + name;
  599. if (names.Contains(name)) continue;
  600. // SQL 语句中必须包含此参数。
  601. var lname = name.Lower();
  602. if (!lsql.Contains(lname)) continue;
  603. var p = dbClient.Parameter(name, kvp.Value);
  604. ps.Add(p);
  605. names.Add(name);
  606. }
  607. return ps;
  608. }
  609. #endregion
  610. #region SQL
  611. /// <summary>对文本转义,符合 SQL 安全性。可根据字段类型限制 UTF-8 字节数,默认为 0 时不限制字节数。</summary>
  612. public static string Escape(this string text, int bytes = 0)
  613. {
  614. if (text.IsEmpty()) return "";
  615. var t = text ?? "";
  616. t = t.Replace("\\", "\\\\");
  617. t = t.Replace("'", "\\'");
  618. t = t.Replace("\n", "\\n");
  619. t = t.Replace("\r", "\\r");
  620. t = t.Replace("\b", "\\b");
  621. t = t.Replace("\t", "\\t");
  622. t = t.Replace("\f", "\\f");
  623. if (bytes > 5)
  624. {
  625. if (t.Bytes(Encoding.UTF8).Length > bytes)
  626. {
  627. while (true)
  628. {
  629. t = t.Substring(0, t.Length - 1);
  630. if (t.Bytes(Encoding.UTF8).Length <= (bytes - 4)) break;
  631. }
  632. t = t + " ...";
  633. }
  634. }
  635. return t;
  636. }
  637. /// <summary>限定名称文本,只允许包含字母、数字和下划线。</summary>
  638. public static string SafeName(this string name) => TextUtility.Restrict(name, "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  639. #endregion
  640. #region 数据模型 -> DataTable
  641. /// <summary>将多个实体元素转换为 DataTable。</summary>
  642. /// <typeparam name="T">实体元素的类型。</typeparam>
  643. /// <param name="items">实体元素。</param>
  644. /// <param name="tableName">设置 <see cref="DataTable"/> 的名称。</param>
  645. /// <exception cref="ArgumentNullException"></exception>
  646. /// <exception cref="DuplicateNameException"></exception>
  647. /// <exception cref="InvalidExpressionException"></exception>
  648. public static DataTable DataTable<T>(this IEnumerable<T> items, string tableName = null)
  649. {
  650. if (items == null) throw new ArgumentNullException(nameof(items));
  651. // 解析表结构。
  652. var it = typeof(T);
  653. var ts = TableStructure.Parse(it, true, true);
  654. if (ts == null || ts.Columns == null || ts.Columns.Length < 1)
  655. {
  656. foreach (var item in items)
  657. {
  658. if (item == null) continue;
  659. var itemType = item.GetType();
  660. ts = TableStructure.Parse(itemType, true, true);
  661. if (ts == null) throw new TypeLoadException($"无法解析 {itemType.FullName} 的结构。");
  662. it = itemType;
  663. break;
  664. }
  665. if (ts == null) throw new TypeLoadException($"无法解析 {it.FullName} 的结构。");
  666. }
  667. var cas = ts.Columns;
  668. var width = cas.Length;
  669. if (width < 1) throw new TypeLoadException($"类型 {it.FullName} 的结构中没有列。");
  670. // 初始化列。
  671. var table = new DataTable();
  672. var pis = new PropertyInfo[width];
  673. var fts = new Type[width];
  674. for (var i = 0; i < width; i++)
  675. {
  676. var ca = cas[i];
  677. var pi = ca.Property;
  678. var pt = pi.PropertyType;
  679. pis[i] = pi;
  680. var ft = pt;
  681. if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
  682. {
  683. pt.GetGenericArguments();
  684. ft = Nullable.GetUnderlyingType(pt);
  685. }
  686. fts[i] = ft;
  687. var column = new DataColumn(ca.Field, ft);
  688. column.AllowDBNull = true;
  689. table.Columns.Add(column);
  690. }
  691. // 添加行。
  692. foreach (var item in items)
  693. {
  694. if (item == null) continue;
  695. var values = new ArrayBuilder<object>(width);
  696. for (var i = 0; i < width; i++)
  697. {
  698. var value = pis[i].GetValue(item, null);
  699. if (value is DateTime dt)
  700. {
  701. if (dt.Year < 1753)
  702. {
  703. values.Add(DBNull.Value);
  704. continue;
  705. }
  706. }
  707. values.Add(value);
  708. }
  709. table.Rows.Add(values.Export());
  710. }
  711. if (tableName.NotEmpty()) table.TableName = tableName;
  712. else if (ts.TableName.NotEmpty()) table.TableName = ts.TableName;
  713. return table;
  714. }
  715. #endregion
  716. #region DataTable 序列化
  717. /// <summary>转换 <see cref="System.Data.DataTable"/> 到 <see cref="ObjectSet{T}"/> 数组,每行记录为一个 ObjectSet 对象。</summary>
  718. /// <returns>当参数 table 无效时返回 0 长度的 <see cref="ObjectSet{T}"/> 数组。</returns>
  719. public static ObjectSet[] ObjectSet(this DataTable table)
  720. {
  721. if (table == null) return new ObjectSet[0];
  722. var columns = table.Columns.Count;
  723. var fields = new string[columns];
  724. for (var c = 0; c < columns; c++) fields[c] = table.Columns[c].ColumnName;
  725. var rows = table.Rows.Count;
  726. var dicts = new Dictionary<string, object>[rows];
  727. for (var r = 0; r < table.Rows.Count; r++)
  728. {
  729. var dict = new Dictionary<string, object>(columns);
  730. for (var c = 0; c < columns; c++)
  731. {
  732. var field = fields[c];
  733. if (string.IsNullOrEmpty(field)) continue;
  734. if (dict.ContainsKey(field)) continue;
  735. var v = table.Rows[r][c];
  736. if (v.IsNull()) v = null;
  737. dict.Add(field, v);
  738. }
  739. dicts[r] = dict;
  740. }
  741. var oss = new ObjectSet[rows];
  742. for (var i = 0; i < rows; i++) oss[i] = new ObjectSet(dicts[i]);
  743. return oss;
  744. }
  745. /// <summary>转换为 Json 对象。</summary>
  746. public static Json ToJson(this DataTable table, Func<DateTime, string> dateTimeFormatter = null)
  747. {
  748. if (table == null) return null;
  749. var columns = ToJson(table.Columns);
  750. var rows = ToJson(table.Rows);
  751. var jsonObject = Json.NewObject();
  752. jsonObject.SetProperty("columns", columns);
  753. jsonObject.SetProperty("rows", rows);
  754. return jsonObject;
  755. }
  756. /// <summary>转换为 Json 对象。</summary>
  757. public static Json ToJson(this DataColumnCollection columns)
  758. {
  759. if (columns == null) return null;
  760. var json = Json.NewArray();
  761. var count = columns.Count;
  762. for (var c = 0; c < count; c++)
  763. {
  764. var dc = columns[c];
  765. var column = Json.NewObject();
  766. column.SetProperty("name", dc.ColumnName);
  767. column.SetProperty("type", dc.DataType.FullName);
  768. json.AddItem(column);
  769. }
  770. return json;
  771. }
  772. /// <summary>转换为 Json 对象。</summary>
  773. public static Json ToJson(this DataRowCollection rows, Func<DateTime, object> dateTimeFormatter = null)
  774. {
  775. if (rows == null) return null;
  776. var json = Json.NewArray();
  777. var count = rows.Count;
  778. for (var r = 0; r < count; r++)
  779. {
  780. json.AddItem(ToJson(rows[r], dateTimeFormatter));
  781. }
  782. return json;
  783. }
  784. /// <summary>转换为 Json 对象。</summary>
  785. public static Json ToJson(this DataRow row, Func<DateTime, object> dateTimeFormatter = null)
  786. {
  787. if (row == null) return null;
  788. var cells = row.ItemArray;
  789. var count = cells.Length;
  790. var json = Json.NewArray();
  791. for (var c = 0; c < count; c++)
  792. {
  793. var value = cells[c];
  794. if (value == null || value.Equals(DBNull.Value))
  795. {
  796. json.AddItem();
  797. continue;
  798. }
  799. if (value is DateTime vDateTime)
  800. {
  801. if (dateTimeFormatter == null)
  802. {
  803. json.AddItem(Json.SerializeDateTime(vDateTime));
  804. continue;
  805. }
  806. else
  807. {
  808. value = dateTimeFormatter.Invoke(vDateTime);
  809. if (value == null || value.Equals(DBNull.Value))
  810. {
  811. json.AddItem();
  812. continue;
  813. }
  814. }
  815. }
  816. if (value is string @string) json.AddItem(@string);
  817. else if (value is byte @byte) json.AddItem(@byte);
  818. else if (value is short @short) json.AddItem(@short);
  819. else if (value is int @int) json.AddItem(@int);
  820. else if (value is long @long) json.AddItem(@long);
  821. else if (value is float @float) json.AddItem(@float);
  822. else if (value is double @double) json.AddItem(@double);
  823. else if (value is decimal @decimal) json.AddItem(@decimal);
  824. else if (value is bool @bool) json.AddItem(@bool);
  825. else if (value is byte[] bytes) json.AddItem(bytes.Base64());
  826. else json.AddItem(TextUtility.Text(value));
  827. }
  828. return json;
  829. }
  830. /// <summary>转换 <see cref="DataTable"/> 为 CSV 文本,不存在表时返回 NULL 值。可指定是否包含表头。</summary>
  831. public static string Csv(DataTable table, bool withHead = false)
  832. {
  833. if (table == null) return null;
  834. var columns = table.Columns.Count;
  835. if (columns < 1) return "";
  836. var sb = new StringBuilder();
  837. if (withHead)
  838. {
  839. for (var c = 0; c < columns; c++)
  840. {
  841. var v = table.Columns[c].ColumnName;
  842. CsvCell(sb, c, v);
  843. }
  844. }
  845. var rows = table.Rows.Count;
  846. for (var r = 0; r < rows; r++)
  847. {
  848. var row = table.Rows[r];
  849. if (withHead || r > 0) sb.Append("\r\n");
  850. for (var c = 0; c < columns; c++) CsvCell(sb, c, row[c]);
  851. }
  852. return sb.ToString();
  853. }
  854. private static void CsvCell(StringBuilder sb, int c, object v)
  855. {
  856. if (c > 0) sb.Append(",");
  857. if (v == null || v.Equals(DBNull.Value)) return;
  858. if (v is bool @bool)
  859. {
  860. sb.Append(@bool ? "TRUE" : "FALSE");
  861. return;
  862. }
  863. if (v is DateTime @datetime)
  864. {
  865. sb.Append(@datetime.Lucid());
  866. return;
  867. }
  868. 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)
  869. {
  870. sb.Append(v.ToString());
  871. return;
  872. }
  873. if (v is char)
  874. {
  875. sb.Append((char)v);
  876. return;
  877. }
  878. var s = (v is string @string) ? @string : v.ToString();
  879. var length = s.Length;
  880. if (length < 1) return;
  881. var quote = false;
  882. var comma = false;
  883. var newline = false;
  884. for (var i = 0; i < length; i++)
  885. {
  886. var @char = s[i];
  887. if (@char == '\"') quote = true;
  888. else if (@char == ',') comma = true;
  889. else if (@char == '\r') newline = false;
  890. else if (@char == '\n') newline = false;
  891. }
  892. if (quote || comma || newline)
  893. {
  894. sb.Append("\"");
  895. s = s.Replace("\"", "\"\"");
  896. sb.Append(s);
  897. sb.Append("\"");
  898. }
  899. else sb.Append(s);
  900. }
  901. #endregion
  902. #region DataTable 快捷操作
  903. /// <summary>获取默认表中指定单元格的内容。</summary>
  904. /// <param name="table">数据表。</param>
  905. /// <param name="rowIndex">行索引,从 0 开始。</param>
  906. /// <param name="columnIndex">列索引,从 0 开始。</param>
  907. public static object Value(this DataTable table, int rowIndex, int columnIndex)
  908. {
  909. if (table != null)
  910. {
  911. if (rowIndex >= 0 && rowIndex < table.Rows.Count)
  912. {
  913. if (columnIndex >= 0 && columnIndex < table.Columns.Count)
  914. {
  915. var value = table.Rows[rowIndex][columnIndex];
  916. if (value == null || value.Equals(DBNull.Value)) return null;
  917. return value;
  918. }
  919. }
  920. }
  921. return null;
  922. }
  923. /// <summary>获取默认表中指定单元的内容。</summary>
  924. /// <param name="table">数据表。</param>
  925. /// <param name="rowIndex">行索引,从 0 开始。</param>
  926. /// <param name="columnName">列名称/字段名称,此名称不区分大小写。</param>
  927. public static object Value(this DataTable table, int rowIndex, string columnName)
  928. {
  929. if (table != null && !string.IsNullOrEmpty(columnName))
  930. {
  931. if ((rowIndex < table.Rows.Count) && (rowIndex >= 0))
  932. {
  933. try
  934. {
  935. var value = table.Rows[rowIndex][columnName];
  936. if (value == null || value.Equals(DBNull.Value)) return null;
  937. return value;
  938. }
  939. catch { }
  940. }
  941. }
  942. return null;
  943. }
  944. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  945. public static Class<DateTime> DateTime(this DataTable table, int row, int column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  946. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  947. public static Class<DateTime> DateTime(this DataTable table, int row, string column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  948. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  949. public static Int32 Int32(this DataTable table, int row, int column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  950. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  951. public static Int32 Int32(this DataTable table, int row, string column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  952. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  953. public static Int64 Int64(this DataTable table, int row, int column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  954. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  955. public static Int64 Int64(this DataTable table, int row, string column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  956. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  957. public static Decimal Decimal(this DataTable table, int row, int column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  958. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  959. public static Decimal Decimal(this DataTable table, int row, string column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  960. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>>
  961. public static Double Double(this DataTable table, int row, int column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  962. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>>
  963. public static Double Double(this DataTable table, int row, string column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  964. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  965. public static string Text(this DataTable table, int row, int column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  966. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  967. public static string Text(this DataTable table, int row, string column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  968. #endregion
  969. #region Dynamic
  970. #if NET40_OR_GREATER
  971. /// <summary>转换 ObjectSet 数组为 dynamic 数组。</summary>
  972. public static dynamic[] Dynamic(this ObjectSet[] oss)
  973. {
  974. if (oss == null) return new dynamic[0];
  975. var eos = oss.Expando();
  976. var ds = new dynamic[eos.Length];
  977. eos.CopyTo(ds, 0);
  978. return ds;
  979. }
  980. #endif
  981. #endregion
  982. #region 表达式计算
  983. /// <summary>计算文本表达式。</summary>
  984. public static object Compute(string expression)
  985. {
  986. using (var table = new DataTable())
  987. {
  988. var result = table.Compute(expression, null);
  989. if (result.IsNull()) return null;
  990. return result;
  991. }
  992. }
  993. #endregion
  994. }
  995. }