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.

1197 lines
51 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
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
2 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
2 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
2 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
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(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. InTransaction<object>(source, () =>
  528. {
  529. action.Invoke();
  530. return null;
  531. });
  532. }
  533. /// <summary>启动事务,执行指定的过程并在完成后提交事务。若过程被异常打断,则回滚事务。</summary>
  534. /// <exception cref="ArgumentNullException"></exception>
  535. /// <exception cref="SqlException"></exception>
  536. public static T InTransaction<T>(this IDbAdo source, Func<T> func)
  537. {
  538. // 检查参数。
  539. if (source == null) throw new ArgumentNullException(nameof(source), "数据源无效。");
  540. if (func == null) throw new ArgumentNullException(nameof(func), "没有指定要在事物中执行的程序。");
  541. // 已经存在事务。
  542. if (source.Transaction != null) return func.Invoke();
  543. // 启动事务。
  544. var begin = source.Begin();
  545. if (begin.NotEmpty()) throw new SqlException("无法启动事务:" + begin);
  546. var result = default(T);
  547. var success = false;
  548. try
  549. {
  550. // 在事务内运行。
  551. result = func.Invoke();
  552. success = true;
  553. }
  554. finally
  555. {
  556. if (success)
  557. {
  558. // 执行成功,提交事务。
  559. var commit = source.Commit();
  560. if (!string.IsNullOrEmpty(commit)) throw new SqlException(commit);
  561. }
  562. else
  563. {
  564. // 执行失败,回滚事务。
  565. try { source.Rollback(); } catch { }
  566. }
  567. }
  568. return result;
  569. }
  570. #endregion
  571. #region Parameter
  572. /// <exception cref="ArgumentNullException"></exception>
  573. static List<IDataParameter> ParametersByProperites(IDbAdo dbClient, string sql, object parameters)
  574. {
  575. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  576. if (parameters == null) return null;
  577. var lsql = sql.Lower();
  578. var type = parameters.GetType();
  579. var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  580. var count = properties.Length;
  581. var dict = new Dictionary<string, object>(count);
  582. for (var i = 0; i < count; i++)
  583. {
  584. var property = properties[i];
  585. // 属性必须能够获取值。
  586. var getter = property.GetGetMethod();
  587. if (getter == null) continue;
  588. // 属性值必须有效。
  589. var name = property.Name;
  590. if (name.IsEmpty()) continue;
  591. // 属性不可重复。
  592. if (!name.StartsWith("@")) name = "@" + name;
  593. if (dict.ContainsKey(name)) continue;
  594. // SQL 语句中必须包含此参数。
  595. var lname = name.Lower();
  596. if (!lsql.Contains(lname)) continue;
  597. // 加入字典。
  598. var value = getter.Invoke(parameters, null);
  599. dict.Add(name, value);
  600. }
  601. if (dict.Count < 1) return null;
  602. var ps = new List<IDataParameter>();
  603. foreach (var kvp in dict)
  604. {
  605. var p = dbClient.Parameter(kvp.Key, kvp.Value);
  606. ps.Add(p);
  607. }
  608. return ps;
  609. }
  610. /// <exception cref="ArgumentNullException"></exception>
  611. static List<IDataParameter> Parameters(IDbAdo dbClient, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
  612. {
  613. if (dbClient == null) throw new ArgumentNullException(nameof(dbClient));
  614. if (parameters == null) return null;
  615. var lsql = sql.Lower();
  616. var names = new List<string>(20);
  617. var ps = new List<IDataParameter>(20);
  618. foreach (var kvp in parameters)
  619. {
  620. var name = kvp.Key;
  621. if (name.IsEmpty()) continue;
  622. // 属性不可重复。
  623. if (!name.StartsWith("@")) name = "@" + name;
  624. if (names.Contains(name)) continue;
  625. // SQL 语句中必须包含此参数。
  626. var lname = name.Lower();
  627. if (!lsql.Contains(lname)) continue;
  628. var p = dbClient.Parameter(name, kvp.Value);
  629. ps.Add(p);
  630. names.Add(name);
  631. }
  632. return ps;
  633. }
  634. #endregion
  635. #region SQL
  636. /// <summary>对文本转义,符合 SQL 安全性。可根据字段类型限制 UTF-8 字节数,默认为 0 时不限制字节数。</summary>
  637. public static string Escape(this string text, int bytes = 0)
  638. {
  639. if (text.IsEmpty()) return "";
  640. var t = text ?? "";
  641. t = t.Replace("\\", "\\\\");
  642. t = t.Replace("'", "\\'");
  643. t = t.Replace("\n", "\\n");
  644. t = t.Replace("\r", "\\r");
  645. t = t.Replace("\b", "\\b");
  646. t = t.Replace("\t", "\\t");
  647. t = t.Replace("\f", "\\f");
  648. if (bytes > 5)
  649. {
  650. if (t.Bytes(Encoding.UTF8).Length > bytes)
  651. {
  652. while (true)
  653. {
  654. t = t.Substring(0, t.Length - 1);
  655. if (t.Bytes(Encoding.UTF8).Length <= (bytes - 4)) break;
  656. }
  657. t = t + " ...";
  658. }
  659. }
  660. return t;
  661. }
  662. /// <summary>限定名称文本,只允许包含字母、数字和下划线。</summary>
  663. public static string SafeName(this string name) => TextUtility.Restrict(name, "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  664. #endregion
  665. #region 数据模型 -> DataTable
  666. /// <summary>将多个实体元素转换为 DataTable。</summary>
  667. /// <typeparam name="T">实体元素的类型。</typeparam>
  668. /// <param name="items">实体元素。</param>
  669. /// <param name="tableName">设置 <see cref="DataTable"/> 的名称。</param>
  670. /// <exception cref="ArgumentNullException"></exception>
  671. /// <exception cref="DuplicateNameException"></exception>
  672. /// <exception cref="InvalidExpressionException"></exception>
  673. public static DataTable DataTable<T>(this IEnumerable<T> items, string tableName = null)
  674. {
  675. if (items == null) throw new ArgumentNullException(nameof(items));
  676. // 解析表结构。
  677. var it = typeof(T);
  678. var ts = TableStructure.Parse(it, true, true);
  679. if (ts == null || ts.Columns == null || ts.Columns.Length < 1)
  680. {
  681. foreach (var item in items)
  682. {
  683. if (item == null) continue;
  684. var itemType = item.GetType();
  685. ts = TableStructure.Parse(itemType, true, true);
  686. if (ts == null) throw new TypeLoadException($"无法解析 {itemType.FullName} 的结构。");
  687. it = itemType;
  688. break;
  689. }
  690. if (ts == null) throw new TypeLoadException($"无法解析 {it.FullName} 的结构。");
  691. }
  692. var cas = ts.Columns;
  693. var width = cas.Length;
  694. if (width < 1) throw new TypeLoadException($"类型 {it.FullName} 的结构中没有列。");
  695. // 初始化列。
  696. var table = new DataTable();
  697. var pis = new PropertyInfo[width];
  698. var fts = new Type[width];
  699. for (var i = 0; i < width; i++)
  700. {
  701. var ca = cas[i];
  702. var pi = ca.Property;
  703. var pt = pi.PropertyType;
  704. pis[i] = pi;
  705. var ft = pt;
  706. if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
  707. {
  708. pt.GetGenericArguments();
  709. ft = Nullable.GetUnderlyingType(pt);
  710. }
  711. fts[i] = ft;
  712. var column = new DataColumn(ca.Field, ft);
  713. column.AllowDBNull = true;
  714. table.Columns.Add(column);
  715. }
  716. // 添加行。
  717. foreach (var item in items)
  718. {
  719. if (item == null) continue;
  720. var values = new ArrayBuilder<object>(width);
  721. for (var i = 0; i < width; i++)
  722. {
  723. var value = pis[i].GetValue(item, null);
  724. if (value is DateTime dt)
  725. {
  726. if (dt.Year < 1753)
  727. {
  728. values.Add(DBNull.Value);
  729. continue;
  730. }
  731. }
  732. values.Add(value);
  733. }
  734. table.Rows.Add(values.Export());
  735. }
  736. if (tableName.NotEmpty()) table.TableName = tableName;
  737. else if (ts.TableName.NotEmpty()) table.TableName = ts.TableName;
  738. return table;
  739. }
  740. #endregion
  741. #region DataTable 序列化
  742. /// <summary>转换 <see cref="System.Data.DataTable"/> 到 <see cref="ObjectSet{T}"/> 数组,每行记录为一个 ObjectSet 对象。</summary>
  743. /// <returns>当参数 table 无效时返回 0 长度的 <see cref="ObjectSet{T}"/> 数组。</returns>
  744. public static ObjectSet[] ObjectSet(this DataTable table)
  745. {
  746. if (table == null) return new ObjectSet[0];
  747. var columns = table.Columns.Count;
  748. var fields = new string[columns];
  749. for (var c = 0; c < columns; c++) fields[c] = table.Columns[c].ColumnName;
  750. var rows = table.Rows.Count;
  751. var dicts = new Dictionary<string, object>[rows];
  752. for (var r = 0; r < table.Rows.Count; r++)
  753. {
  754. var dict = new Dictionary<string, object>(columns);
  755. for (var c = 0; c < columns; c++)
  756. {
  757. var field = fields[c];
  758. if (string.IsNullOrEmpty(field)) continue;
  759. if (dict.ContainsKey(field)) continue;
  760. var v = table.Rows[r][c];
  761. if (v.IsNull()) v = null;
  762. dict.Add(field, v);
  763. }
  764. dicts[r] = dict;
  765. }
  766. var oss = new ObjectSet[rows];
  767. for (var i = 0; i < rows; i++) oss[i] = new ObjectSet(dicts[i]);
  768. return oss;
  769. }
  770. /// <summary>转换为 Json 对象。</summary>
  771. public static Json ToJson(this DataTable table, Func<DateTime, string> dateTimeFormatter = null)
  772. {
  773. if (table == null) return null;
  774. var columns = ToJson(table.Columns);
  775. var rows = ToJson(table.Rows);
  776. var jsonObject = Json.NewObject();
  777. jsonObject.SetProperty("columns", columns);
  778. jsonObject.SetProperty("rows", rows);
  779. return jsonObject;
  780. }
  781. /// <summary>转换为 Json 对象。</summary>
  782. public static Json ToJson(this DataColumnCollection columns)
  783. {
  784. if (columns == null) return null;
  785. var json = Json.NewArray();
  786. var count = columns.Count;
  787. for (var c = 0; c < count; c++)
  788. {
  789. var dc = columns[c];
  790. var column = Json.NewObject();
  791. column.SetProperty("name", dc.ColumnName);
  792. column.SetProperty("type", dc.DataType.FullName);
  793. json.AddItem(column);
  794. }
  795. return json;
  796. }
  797. /// <summary>转换为 Json 对象。</summary>
  798. public static Json ToJson(this DataRowCollection rows, Func<DateTime, object> dateTimeFormatter = null)
  799. {
  800. if (rows == null) return null;
  801. var json = Json.NewArray();
  802. var count = rows.Count;
  803. for (var r = 0; r < count; r++)
  804. {
  805. json.AddItem(ToJson(rows[r], dateTimeFormatter));
  806. }
  807. return json;
  808. }
  809. /// <summary>转换为 Json 对象。</summary>
  810. public static Json ToJson(this DataRow row, Func<DateTime, object> dateTimeFormatter = null)
  811. {
  812. if (row == null) return null;
  813. var cells = row.ItemArray;
  814. var count = cells.Length;
  815. var json = Json.NewArray();
  816. for (var c = 0; c < count; c++)
  817. {
  818. var value = cells[c];
  819. if (value == null || value.Equals(DBNull.Value))
  820. {
  821. json.AddItem();
  822. continue;
  823. }
  824. if (value is DateTime vDateTime)
  825. {
  826. if (dateTimeFormatter == null)
  827. {
  828. json.AddItem(Json.SerializeDateTime(vDateTime));
  829. continue;
  830. }
  831. else
  832. {
  833. value = dateTimeFormatter.Invoke(vDateTime);
  834. if (value == null || value.Equals(DBNull.Value))
  835. {
  836. json.AddItem();
  837. continue;
  838. }
  839. }
  840. }
  841. if (value is string @string) json.AddItem(@string);
  842. else if (value is byte @byte) json.AddItem(@byte);
  843. else if (value is short @short) json.AddItem(@short);
  844. else if (value is int @int) json.AddItem(@int);
  845. else if (value is long @long) json.AddItem(@long);
  846. else if (value is float @float) json.AddItem(@float);
  847. else if (value is double @double) json.AddItem(@double);
  848. else if (value is decimal @decimal) json.AddItem(@decimal);
  849. else if (value is bool @bool) json.AddItem(@bool);
  850. else if (value is byte[] bytes) json.AddItem(bytes.Base64());
  851. else json.AddItem(TextUtility.Text(value));
  852. }
  853. return json;
  854. }
  855. /// <summary>转换 <see cref="DataTable"/> 为 CSV 文本,不存在表时返回 NULL 值。可指定是否包含表头。</summary>
  856. public static string Csv(DataTable table, bool withHead = false)
  857. {
  858. if (table == null) return null;
  859. var columns = table.Columns.Count;
  860. if (columns < 1) return "";
  861. var sb = new StringBuilder();
  862. if (withHead)
  863. {
  864. for (var c = 0; c < columns; c++)
  865. {
  866. var v = table.Columns[c].ColumnName;
  867. CsvCell(sb, c, v);
  868. }
  869. }
  870. var rows = table.Rows.Count;
  871. for (var r = 0; r < rows; r++)
  872. {
  873. var row = table.Rows[r];
  874. if (withHead || r > 0) sb.Append("\r\n");
  875. for (var c = 0; c < columns; c++) CsvCell(sb, c, row[c]);
  876. }
  877. return sb.ToString();
  878. }
  879. private static void CsvCell(StringBuilder sb, int c, object v)
  880. {
  881. if (c > 0) sb.Append(",");
  882. if (v == null || v.Equals(DBNull.Value)) return;
  883. if (v is bool @bool)
  884. {
  885. sb.Append(@bool ? "TRUE" : "FALSE");
  886. return;
  887. }
  888. if (v is DateTime @datetime)
  889. {
  890. sb.Append(@datetime.Lucid());
  891. return;
  892. }
  893. 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)
  894. {
  895. sb.Append(v.ToString());
  896. return;
  897. }
  898. if (v is char)
  899. {
  900. sb.Append((char)v);
  901. return;
  902. }
  903. var s = (v is string @string) ? @string : v.ToString();
  904. var length = s.Length;
  905. if (length < 1) return;
  906. var quote = false;
  907. var comma = false;
  908. var newline = false;
  909. for (var i = 0; i < length; i++)
  910. {
  911. var @char = s[i];
  912. if (@char == '\"') quote = true;
  913. else if (@char == ',') comma = true;
  914. else if (@char == '\r') newline = false;
  915. else if (@char == '\n') newline = false;
  916. }
  917. if (quote || comma || newline)
  918. {
  919. sb.Append("\"");
  920. s = s.Replace("\"", "\"\"");
  921. sb.Append(s);
  922. sb.Append("\"");
  923. }
  924. else sb.Append(s);
  925. }
  926. #endregion
  927. #region DataTable 快捷操作
  928. /// <summary>获取默认表中指定单元格的内容。</summary>
  929. /// <param name="table">数据表。</param>
  930. /// <param name="rowIndex">行索引,从 0 开始。</param>
  931. /// <param name="columnIndex">列索引,从 0 开始。</param>
  932. public static object Value(this DataTable table, int rowIndex, int columnIndex)
  933. {
  934. if (table != null)
  935. {
  936. if (rowIndex >= 0 && rowIndex < table.Rows.Count)
  937. {
  938. if (columnIndex >= 0 && columnIndex < table.Columns.Count)
  939. {
  940. var value = table.Rows[rowIndex][columnIndex];
  941. if (value == null || value.Equals(DBNull.Value)) return null;
  942. return value;
  943. }
  944. }
  945. }
  946. return null;
  947. }
  948. /// <summary>获取默认表中指定单元的内容。</summary>
  949. /// <param name="table">数据表。</param>
  950. /// <param name="rowIndex">行索引,从 0 开始。</param>
  951. /// <param name="columnName">列名称/字段名称,此名称不区分大小写。</param>
  952. public static object Value(this DataTable table, int rowIndex, string columnName)
  953. {
  954. if (table != null && !string.IsNullOrEmpty(columnName))
  955. {
  956. if ((rowIndex < table.Rows.Count) && (rowIndex >= 0))
  957. {
  958. try
  959. {
  960. var value = table.Rows[rowIndex][columnName];
  961. if (value == null || value.Equals(DBNull.Value)) return null;
  962. return value;
  963. }
  964. catch { }
  965. }
  966. }
  967. return null;
  968. }
  969. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  970. public static Class<DateTime> DateTime(this DataTable table, int row, int column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  971. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  972. public static Class<DateTime> DateTime(this DataTable table, int row, string column) => table == null ? null : ClockUtility.DateTime(table.Value(row, column));
  973. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  974. public static Int32 Int32(this DataTable table, int row, int column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  975. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  976. public static Int32 Int32(this DataTable table, int row, string column) => table == null ? 0 : NumberUtility.Int32(table.Value(row, column));
  977. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  978. public static Int64 Int64(this DataTable table, int row, int column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  979. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  980. public static Int64 Int64(this DataTable table, int row, string column) => table == null ? 0L : NumberUtility.Int64(table.Value(row, column));
  981. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  982. public static Decimal Decimal(this DataTable table, int row, int column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  983. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  984. public static Decimal Decimal(this DataTable table, int row, string column) => table == null ? 0M : NumberUtility.Decimal(table.Value(row, column));
  985. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>>
  986. public static Double Double(this DataTable table, int row, int column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  987. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>>
  988. public static Double Double(this DataTable table, int row, string column) => table == null ? 0D : NumberUtility.Double(table.Value(row, column));
  989. /// <summary>获取默认表中指定单元格的内容。从第 0 行第 0 列开始。</summary>
  990. public static string Text(this DataTable table, int row, int column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  991. /// <summary>获取默认表中指定单元格的内容。从第 0 行开始。</summary>
  992. public static string Text(this DataTable table, int row, string column) => table == null ? null : TextUtility.Text(table.Value(row, column));
  993. #endregion
  994. #region Dynamic
  995. #if NET40_OR_GREATER
  996. /// <summary>转换 ObjectSet 数组为 dynamic 数组。</summary>
  997. public static dynamic[] Dynamic(this ObjectSet[] oss)
  998. {
  999. if (oss == null) return new dynamic[0];
  1000. var eos = oss.Expando();
  1001. var ds = new dynamic[eos.Length];
  1002. eos.CopyTo(ds, 0);
  1003. return ds;
  1004. }
  1005. #endif
  1006. #endregion
  1007. #region 表达式计算
  1008. /// <summary>计算文本表达式。</summary>
  1009. public static object Compute(string expression)
  1010. {
  1011. using (var table = new DataTable())
  1012. {
  1013. var result = table.Compute(expression, null);
  1014. if (result.IsNull()) return null;
  1015. return result;
  1016. }
  1017. }
  1018. #endregion
  1019. }
  1020. }