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.

456 lines
19 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Dynamic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. namespace SqlSugar
  9. {
  10. public class ContextMethods : IContextMethods
  11. {
  12. public SqlSugarClient Context { get; set; }
  13. #region DataReader
  14. /// <summary>
  15. ///DataReader to Dynamic
  16. /// </summary>
  17. /// <param name="reader"></param>
  18. /// <returns></returns>
  19. public ExpandoObject DataReaderToExpandoObject(IDataReader reader)
  20. {
  21. var result = new ExpandoObject();
  22. var dic = ((IDictionary<string, object>)result);
  23. for (int i = 0; i < reader.FieldCount; i++)
  24. {
  25. try
  26. {
  27. var addItem = reader.GetValue(i);
  28. if (addItem == DBNull.Value)
  29. addItem = null;
  30. dic.Add(reader.GetName(i), addItem);
  31. }
  32. catch
  33. {
  34. dic.Add(reader.GetName(i), null);
  35. }
  36. }
  37. return result;
  38. }
  39. /// <summary>
  40. ///DataReader to Dynamic List
  41. /// </summary>
  42. /// <param name="reader"></param>
  43. /// <returns></returns>
  44. public List<ExpandoObject> DataReaderToExpandoObjectList(IDataReader reader)
  45. {
  46. using (reader)
  47. {
  48. var result = new List<ExpandoObject>();
  49. if (reader != null && !reader.IsClosed)
  50. {
  51. while (reader.Read())
  52. {
  53. result.Add(DataReaderToExpandoObject(reader));
  54. }
  55. }
  56. return result;
  57. }
  58. }
  59. /// <summary>
  60. ///DataReader to DataReaderToDictionary
  61. /// </summary>
  62. /// <param name="reader"></param>
  63. /// <returns></returns>
  64. public Dictionary<string, object> DataReaderToDictionary(IDataReader reader)
  65. {
  66. var result = new Dictionary<string, object>();
  67. for (int i = 0; i < reader.FieldCount; i++)
  68. {
  69. try
  70. {
  71. var addItem = reader.GetValue(i);
  72. if (addItem == DBNull.Value)
  73. addItem = null;
  74. result.Add(reader.GetName(i), addItem);
  75. }
  76. catch
  77. {
  78. result.Add(reader.GetName(i), null);
  79. }
  80. }
  81. return result;
  82. }
  83. /// <summary>
  84. /// DataReaderToDynamicList
  85. /// </summary>
  86. /// <typeparam name="T"></typeparam>
  87. /// <param name="reader"></param>
  88. /// <returns></returns>
  89. public List<T> DataReaderToDynamicList<T>(IDataReader reader)
  90. {
  91. using (reader)
  92. {
  93. var tType = typeof(T);
  94. var classProperties = tType.GetProperties().ToList();
  95. var reval = new List<T>();
  96. if (reader != null && !reader.IsClosed)
  97. {
  98. while (reader.Read())
  99. {
  100. var readerValues = DataReaderToDictionary(reader);
  101. var result = new Dictionary<string, object>();
  102. foreach (var item in classProperties)
  103. {
  104. var name = item.Name;
  105. var typeName = tType.Name;
  106. if (item.PropertyType.IsClass())
  107. {
  108. result.Add(name, DataReaderToDynamicList_Part(readerValues, item, reval));
  109. }
  110. else
  111. {
  112. if (readerValues.Any(it => it.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase)))
  113. {
  114. var addValue = readerValues.ContainsKey(name) ? readerValues[name] : readerValues[name.ToUpper()];
  115. if (addValue == DBNull.Value)
  116. {
  117. if (item.PropertyType.IsIn(UtilConstants.IntType, UtilConstants.DecType, UtilConstants.DobType, UtilConstants.ByteType))
  118. {
  119. addValue = 0;
  120. }
  121. else if (item.PropertyType == UtilConstants.GuidType)
  122. {
  123. addValue = Guid.Empty;
  124. }
  125. else if (item.PropertyType == UtilConstants.DateType)
  126. {
  127. addValue = DateTime.MinValue;
  128. }
  129. else
  130. {
  131. addValue = null;
  132. }
  133. }
  134. else if (item.PropertyType == UtilConstants.IntType)
  135. {
  136. addValue = Convert.ToInt32(addValue);
  137. }
  138. result.Add(name, addValue);
  139. }
  140. }
  141. }
  142. var stringValue = SerializeObject(result);
  143. reval.Add((T)DeserializeObject<T>(stringValue));
  144. }
  145. }
  146. return reval;
  147. }
  148. }
  149. private Dictionary<string, object> DataReaderToDynamicList_Part<T>(Dictionary<string, object> readerValues, PropertyInfo item, List<T> reval)
  150. {
  151. var result = new Dictionary<string, object>();
  152. var type = item.PropertyType;
  153. if (UtilConstants.SugarType == type)
  154. {
  155. return result;
  156. }
  157. if (type.FullName.IsCollectionsList())
  158. {
  159. return null;
  160. }
  161. var classProperties = type.GetProperties().ToList();
  162. foreach (var prop in classProperties)
  163. {
  164. var name = prop.Name;
  165. var typeName = type.Name;
  166. if (prop.PropertyType.IsClass())
  167. {
  168. result.Add(name, DataReaderToDynamicList_Part(readerValues, prop, reval));
  169. }
  170. else
  171. {
  172. var key = typeName + "." + name;
  173. if (readerValues.ContainsKey(key))
  174. {
  175. var addItem = readerValues[key];
  176. if (addItem == DBNull.Value)
  177. addItem = null;
  178. result.Add(name, addItem);
  179. }
  180. }
  181. }
  182. return result;
  183. }
  184. #endregion DataReader
  185. #region Serialize
  186. /// <summary>
  187. /// Serialize Object
  188. /// </summary>
  189. /// <param name="value"></param>
  190. /// <returns></returns>
  191. public string SerializeObject(object value)
  192. {
  193. DependencyManagement.TryJsonNet();
  194. return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SerializeObject(value);
  195. }
  196. /// <summary>
  197. /// Serialize Object
  198. /// </summary>
  199. /// <param name="value"></param>
  200. /// <returns></returns>
  201. public T DeserializeObject<T>(string value)
  202. {
  203. DependencyManagement.TryJsonNet();
  204. return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.DeserializeObject<T>(value);
  205. }
  206. #endregion Serialize
  207. #region Copy Object
  208. /// <summary>
  209. /// Copy new Object
  210. /// </summary>
  211. /// <typeparam name="T"></typeparam>
  212. /// <param name="sourceObject"></param>
  213. /// <returns></returns>
  214. public T TranslateCopy<T>(T sourceObject)
  215. {
  216. if (sourceObject == null) return default(T);
  217. else
  218. {
  219. var jsonString = SerializeObject(sourceObject);
  220. return DeserializeObject<T>(jsonString);
  221. }
  222. }
  223. public SqlSugarClient CopyContext(bool isCopyEvents = false)
  224. {
  225. var newClient = new SqlSugarClient(this.TranslateCopy(Context.CurrentConnectionConfig))
  226. {
  227. MappingColumns = this.TranslateCopy(Context.MappingColumns),
  228. MappingTables = this.TranslateCopy(Context.MappingTables),
  229. IgnoreColumns = this.TranslateCopy(Context.IgnoreColumns)
  230. };
  231. if (isCopyEvents)
  232. {
  233. newClient.Ado.IsEnableLogEvent = Context.Ado.IsEnableLogEvent;
  234. newClient.Ado.LogEventStarting = Context.Ado.LogEventStarting;
  235. newClient.Ado.LogEventCompleted = Context.Ado.LogEventCompleted;
  236. newClient.Ado.ProcessingEventStartingSQL = Context.Ado.ProcessingEventStartingSQL;
  237. }
  238. return newClient;
  239. }
  240. #endregion Copy Object
  241. #region DataTable
  242. public dynamic DataTableToDynamic(DataTable table)
  243. {
  244. var deserializeObject = new List<Dictionary<string, object>>();
  245. Dictionary<string, object> childRow;
  246. foreach (DataRow row in table.Rows)
  247. {
  248. childRow = new Dictionary<string, object>();
  249. foreach (DataColumn col in table.Columns)
  250. {
  251. var addItem = row[col];
  252. if (addItem == DBNull.Value)
  253. addItem = null;
  254. childRow.Add(col.ColumnName, addItem);
  255. }
  256. deserializeObject.Add(childRow);
  257. }
  258. return this.DeserializeObject<dynamic>(this.SerializeObject(deserializeObject));
  259. }
  260. #endregion DataTable
  261. #region Cache
  262. public ICacheService GetReflectionInoCacheInstance()
  263. {
  264. return Context.CurrentConnectionConfig.ConfigureExternalServices.ReflectionInoCacheService;
  265. }
  266. public void RemoveCacheAll()
  267. {
  268. ReflectionInoHelper.RemoveAllCache();
  269. }
  270. public void RemoveCacheAll<T>()
  271. {
  272. ReflectionInoCore<T>.GetInstance().RemoveAllCache();
  273. }
  274. public void RemoveCache<T>(string key)
  275. {
  276. ReflectionInoCore<T>.GetInstance().Remove(key);
  277. }
  278. #endregion Cache
  279. #region Query
  280. public KeyValuePair<string, SugarParameter[]> ConditionalModelToSql(List<IConditionalModel> models, int beginIndex = 0)
  281. {
  282. if (models.IsNullOrEmpty()) return new KeyValuePair<string, SugarParameter[]>();
  283. var builder = new StringBuilder();
  284. var parameters = new List<SugarParameter>();
  285. var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig);
  286. foreach (var model in models)
  287. {
  288. if (model is ConditionalModel)
  289. {
  290. var item = model as ConditionalModel;
  291. var index = models.IndexOf(item) + beginIndex;
  292. var type = index == 0 ? "" : "AND";
  293. if (beginIndex > 0)
  294. {
  295. type = null;
  296. }
  297. var temp = " {0} {1} {2} {3} ";
  298. var parameterName = string.Format("{0}Conditional{1}{2}", sqlBuilder.SqlParameterKeyWord, item.FieldName, index);
  299. switch (item.ConditionalType)
  300. {
  301. case ConditionalType.Equal:
  302. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName);
  303. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  304. break;
  305. case ConditionalType.Like:
  306. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
  307. parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue + "%"));
  308. break;
  309. case ConditionalType.GreaterThan:
  310. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">", parameterName);
  311. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  312. break;
  313. case ConditionalType.GreaterThanOrEqual:
  314. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">=", parameterName);
  315. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  316. break;
  317. case ConditionalType.LessThan:
  318. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<", parameterName);
  319. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  320. break;
  321. case ConditionalType.LessThanOrEqual:
  322. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<=", parameterName);
  323. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  324. break;
  325. case ConditionalType.In:
  326. if (item.FieldValue == null) item.FieldValue = string.Empty;
  327. var inValue1 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")");
  328. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "IN", inValue1);
  329. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  330. break;
  331. case ConditionalType.NotIn:
  332. if (item.FieldValue == null) item.FieldValue = string.Empty;
  333. var inValue2 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")");
  334. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "NOT IN", inValue2);
  335. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  336. break;
  337. case ConditionalType.LikeLeft:
  338. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
  339. parameters.Add(new SugarParameter(parameterName, item.FieldValue + "%"));
  340. break;
  341. case ConditionalType.LikeRight:
  342. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
  343. parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue));
  344. break;
  345. case ConditionalType.NoEqual:
  346. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName);
  347. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  348. break;
  349. case ConditionalType.IsNullOrEmpty:
  350. builder.AppendFormat("{0} ({1}) OR ({2}) ", type, item.FieldName.ToSqlFilter() + " IS NULL ", item.FieldName.ToSqlFilter() + " = '' ");
  351. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  352. break;
  353. case ConditionalType.IsNot:
  354. if (item.FieldValue == null)
  355. {
  356. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), " IS NOT ", "NULL");
  357. }
  358. else
  359. {
  360. builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName);
  361. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  362. }
  363. break;
  364. case ConditionalType.CharIndexLeft:
  365. builder.AppendFormat(temp, type, "CHARINDEX(" + item.FieldName.ToSqlFilter(), ",", parameterName + ")>0");
  366. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  367. break;
  368. case ConditionalType.CharIndexRight:
  369. builder.AppendFormat(temp, type, "CHARINDEX(" + parameterName, ",", item.FieldName.ToSqlFilter() + ")>0");
  370. parameters.Add(new SugarParameter(parameterName, item.FieldValue));
  371. break;
  372. default:
  373. break;
  374. }
  375. }
  376. else
  377. {
  378. var item = model as ConditionalCollections;
  379. if (item != null)
  380. {
  381. foreach (var con in item.ConditionalList)
  382. {
  383. var index = item.ConditionalList.IndexOf(con);
  384. var isFirst = index == 0;
  385. var isLast = index == (item.ConditionalList.Count - 1);
  386. if (isFirst)
  387. {
  388. builder.AppendFormat(" {0} ( ", con.Key.ToString().ToUpper());
  389. }
  390. var conModels = new List<IConditionalModel>();
  391. conModels.Add(con.Value);
  392. var childSqlInfo = ConditionalModelToSql(conModels, 1000 * (1 + index));
  393. if (!isFirst)
  394. {
  395. builder.AppendFormat(" {0} ", con.Key.ToString().ToUpper());
  396. }
  397. builder.Append(childSqlInfo.Key);
  398. parameters.AddRange(childSqlInfo.Value);
  399. if (isLast)
  400. {
  401. builder.Append(" ) ");
  402. }
  403. else
  404. {
  405. }
  406. }
  407. }
  408. }
  409. }
  410. return new KeyValuePair<string, SugarParameter[]>(builder.ToString(), parameters.ToArray());
  411. }
  412. #endregion Query
  413. }
  414. }