EFCoreExt.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace wispro.sp.share
  8. {
  9. [Serializable]
  10. public class ExpressTree {
  11. private ConditionTreeNode root ;
  12. public void AddCondition(LogicEnum logic, FieldCondition fieldCondition)
  13. {
  14. FieldConditionNode rightNode = new FieldConditionNode() { FieldCondition = fieldCondition };
  15. if (root == null)
  16. {
  17. Console.WriteLine("根节点为空时添加!");
  18. root = rightNode;
  19. }
  20. else
  21. {
  22. Console.WriteLine("根节点为空时添加!");
  23. OperateNode root1 = new OperateNode() { Operator = logic };
  24. Console.WriteLine("\t设定右节点!");
  25. root1.Right = rightNode;
  26. Console.WriteLine("\t设定左节点!");
  27. root1.Left = root;
  28. Console.WriteLine("\t设定根节点为操作节点!");
  29. root = root1;
  30. Console.WriteLine((root != null)?"\t根节点不为空": "\t根节点为空");
  31. }
  32. //Console.WriteLine($"表达式: {ToExpressString("s")}");
  33. }
  34. public string ToExpressString(string prefix)
  35. {
  36. if(root == null)
  37. {
  38. return null;
  39. }
  40. else
  41. {
  42. if(root is FieldConditionNode)
  43. {
  44. return ((FieldConditionNode)root).FieldCondition.ToExpressString(prefix);
  45. }
  46. else
  47. {
  48. OperateNode operate = (OperateNode)root;
  49. if(root.Right != null && root.Left != null)
  50. {
  51. ExpressTree leftTree = new ExpressTree() { root = root.Left };
  52. ExpressTree rightTree = new ExpressTree() { root = root.Right };
  53. switch (operate.Operator)
  54. {
  55. case LogicEnum.And:
  56. return $"({leftTree.ToExpressString(prefix)}) && ({rightTree.ToExpressString(prefix)})";
  57. break;
  58. case LogicEnum.Or:
  59. return $"({leftTree.ToExpressString(prefix)}) || ({rightTree.ToExpressString(prefix)})";
  60. break;
  61. default:
  62. return "";
  63. }
  64. }
  65. else
  66. {
  67. throw (new ApplicationException("无效的表达是树!"));
  68. }
  69. }
  70. }
  71. }
  72. }
  73. [Serializable]
  74. public class ConditionTreeNode
  75. {
  76. public ConditionTreeNode Right { get; set; }
  77. public ConditionTreeNode Left { get; set; }
  78. }
  79. [Serializable]
  80. public class OperateNode : ConditionTreeNode
  81. {
  82. public LogicEnum Operator { get; set; }
  83. }
  84. [Serializable]
  85. public class FieldConditionNode : ConditionTreeNode
  86. {
  87. public FieldCondition FieldCondition { get; set; }
  88. }
  89. [Serializable]
  90. public class OrderField
  91. {
  92. /// <summary>
  93. /// 排序栏位
  94. /// </summary>
  95. public string FieldName { get; set; }
  96. /// <summary>
  97. /// 排序 0:顺序;1:倒序
  98. /// </summary>
  99. public int Sort { get; set; }
  100. }
  101. [Serializable]
  102. public class FieldCondition
  103. {
  104. /// <summary>
  105. /// 字段名称
  106. /// </summary>
  107. public string FieldName { get; set; }
  108. /// <summary>
  109. /// 值
  110. /// </summary>
  111. public string Value { get; set; }
  112. /// <summary>
  113. /// 值类型
  114. /// </summary>
  115. public string ValueType { get; set; }
  116. /// <summary>
  117. ///
  118. /// </summary>
  119. public OperatorEnum Operator { get; set; }
  120. public LogicEnum LogicOperate { get; set; }
  121. public string ToExpressString(string prefix)
  122. {
  123. bool isString = (ValueType == typeof(string).ToString());
  124. switch (Operator) {
  125. case OperatorEnum.Contains:
  126. if (isString)
  127. {
  128. return $"{prefix}.{FieldName}.Contains(\"{Value}\")";
  129. }
  130. else
  131. {
  132. throw (new ApplicationException("Contains 操作只对字符字段有效!"));
  133. }
  134. break;
  135. case OperatorEnum.NotContains:
  136. if (isString)
  137. {
  138. return $"!{prefix}.{FieldName}.Contains(\"{Value}\")";
  139. }
  140. else
  141. {
  142. throw (new ApplicationException("Contains 操作只对字符字段有效!"));
  143. }
  144. break;
  145. case OperatorEnum.Equal:
  146. if (isString)
  147. {
  148. return $"{prefix}.{FieldName} == (\"{Value}\")";
  149. }
  150. else
  151. {
  152. return $"{prefix}.{FieldName} == ({Value})";
  153. }
  154. break;
  155. case OperatorEnum.NotEqual:
  156. if (isString)
  157. {
  158. return $"{prefix}.{FieldName} != (\"{Value}\")";
  159. }
  160. else
  161. {
  162. return $"{prefix}.{FieldName} != ({Value})";
  163. }
  164. break;
  165. case OperatorEnum.Greater:
  166. if (isString)
  167. {
  168. return $"{prefix}.{FieldName} > (\"{Value}\")";
  169. }
  170. else
  171. {
  172. return $"{prefix}.{FieldName} > ({Value})";
  173. }
  174. break;
  175. case OperatorEnum.GreaterEqual:
  176. if (isString)
  177. {
  178. return $"{prefix}.{FieldName} >= (\"{Value}\")";
  179. }
  180. else
  181. {
  182. return $"{prefix}.{FieldName} >= ({Value})";
  183. }
  184. break;
  185. case OperatorEnum.Less :
  186. if (isString)
  187. {
  188. return $"{prefix}.{FieldName} < (\"{Value}\")";
  189. }
  190. else
  191. {
  192. return $"{prefix}.{FieldName} < ({Value})";
  193. }
  194. break;
  195. case OperatorEnum.LessEqual:
  196. if (isString)
  197. {
  198. return $"{prefix}.{FieldName} <= (\"{Value}\")";
  199. }
  200. else
  201. {
  202. return $"{prefix}.{FieldName} <= ({Value})";
  203. }
  204. break;
  205. case OperatorEnum.StartsWith:
  206. if (isString)
  207. {
  208. return $"{prefix}.{FieldName}.StartsWith(\"{Value}\")";
  209. }
  210. else
  211. {
  212. throw (new ApplicationException("StartsWith 操作只对字符字段有效!"));
  213. }
  214. break;
  215. case OperatorEnum.EndWith:
  216. if (isString)
  217. {
  218. return $"{prefix}.{FieldName}.EndWith(\"{Value}\")";
  219. }
  220. else
  221. {
  222. throw (new ApplicationException("EndWith 操作只对字符字段有效!"));
  223. }
  224. break;
  225. //case OperatorEnum.In:
  226. // break;
  227. //case OperatorEnum.Between:
  228. // break;
  229. default:
  230. throw (new ApplicationException("还未实现的操作符号!"));
  231. }
  232. }
  233. }
  234. [Serializable]
  235. public enum OperatorEnum
  236. {
  237. Contains,
  238. Equal,
  239. Greater,
  240. GreaterEqual,
  241. Less,
  242. LessEqual,
  243. NotEqual,
  244. In,
  245. Between,
  246. StartsWith,
  247. EndWith,
  248. NotContains
  249. }
  250. [Serializable]
  251. public enum LogicEnum
  252. {
  253. And,
  254. Or
  255. }
  256. public static class EFCoreExt
  257. {
  258. public static IQueryable<T> OrderConditions<T>(this IQueryable<T> query, IList<OrderField> orderConditions)
  259. {
  260. foreach (var orderinfo in orderConditions)
  261. {
  262. //var t = typeof(T);
  263. //var propertyInfo = t.GetProperty(orderinfo.FieldName);
  264. //var parameter = Expression.Parameter(t);
  265. //Expression propertySelector = Expression.Property(parameter, propertyInfo);
  266. //var orderby = Expression.Lambda<Func<T, dynamic>>(propertySelector, parameter);
  267. //if (orderinfo.Sort == 1)
  268. // query = query.OrderByDescending(orderby);
  269. //else
  270. // query = query.OrderBy(orderby);
  271. var parameter = Expression.Parameter(typeof(T));
  272. var prop = Expression.PropertyOrField(parameter, orderinfo.FieldName);
  273. var sortLambda = Expression.Lambda(prop, parameter);
  274. Expression<Func<IOrderedQueryable<T>>> sortMethod = (() => query.OrderBy<T, object>(k => null));
  275. if(orderinfo.Sort == 1)
  276. {
  277. sortMethod = (() => query.OrderByDescending<T, object>(k => null));
  278. }
  279. var methodCallExpression = (sortMethod.Body as MethodCallExpression);
  280. if (methodCallExpression == null)
  281. throw new Exception("Oops");
  282. var method = methodCallExpression.Method.GetGenericMethodDefinition();
  283. var genericSortMethod = method.MakeGenericMethod(typeof(T), prop.Type);
  284. query = (IQueryable<T>)genericSortMethod.Invoke(query, new object[] { query, sortLambda });
  285. }
  286. return query;
  287. }
  288. public static IOrderedQueryable<TEntityType> SortMeDynamically<TEntityType>( this IQueryable<TEntityType> query, string propertyname)
  289. {
  290. var param = Expression.Parameter(typeof(TEntityType), "s");
  291. var prop = Expression.PropertyOrField(param, propertyname);
  292. var sortLambda = Expression.Lambda(prop, param);
  293. Expression<Func<IOrderedQueryable<TEntityType>>> sortMethod = (() => query.OrderBy<TEntityType, object>(k => null));
  294. var methodCallExpression = (sortMethod.Body as MethodCallExpression);
  295. if (methodCallExpression == null)
  296. throw new Exception("Oops");
  297. var method = methodCallExpression.Method.GetGenericMethodDefinition();
  298. var genericSortMethod = method.MakeGenericMethod(typeof(TEntityType), prop.Type);
  299. var orderedQuery = (IOrderedQueryable<TEntityType>)genericSortMethod.Invoke(query, new object[] { query, sortLambda });
  300. return orderedQuery;
  301. }
  302. public static IQueryable<T> Pager<T>(this IQueryable<T> query, int pageindex, int pagesize, out int itemCount)
  303. {
  304. itemCount = query.Count();
  305. return query.Skip((pageindex - 1) * pagesize).Take(pagesize);
  306. }
  307. }
  308. }