SubDistinctCount.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. namespace SqlSugar
  7. {
  8. public class SubDistinctCount : ISubOperation
  9. {
  10. public bool HasWhere
  11. {
  12. get; set;
  13. }
  14. public string Name
  15. {
  16. get
  17. {
  18. return "DistinctCount";
  19. }
  20. }
  21. public Expression Expression
  22. {
  23. get; set;
  24. }
  25. public int Sort
  26. {
  27. get
  28. {
  29. return 200;
  30. }
  31. }
  32. public ExpressionContext Context
  33. {
  34. get; set;
  35. }
  36. public string GetValue(Expression expression = null)
  37. {
  38. var exp = expression as MethodCallExpression;
  39. var argExp = exp.Arguments[0];
  40. InitType(exp);
  41. var parametres = (argExp as LambdaExpression).Parameters;
  42. if ((argExp as LambdaExpression).Body is UnaryExpression)
  43. {
  44. argExp = ((argExp as LambdaExpression).Body as UnaryExpression).Operand;
  45. }
  46. var argLambda = argExp as LambdaExpression;
  47. if (this.Context.InitMappingInfo != null && argLambda != null && argLambda.Parameters.Count > 0)
  48. {
  49. foreach (var item in argLambda.Parameters)
  50. {
  51. this.Context.InitMappingInfo(item.Type);
  52. }
  53. this.Context.RefreshMapping();
  54. }
  55. var result = "COUNT(DISTINCT " + SubTools.GetMethodValue(Context, argExp, ResolveExpressType.WhereMultiple) + ")";
  56. var selfParameterName = Context.GetTranslationColumnName(parametres.First().Name) + UtilConstants.Dot;
  57. if (this.Context.JoinIndex == 0)
  58. result = result.Replace(selfParameterName, SubTools.GetSubReplace(this.Context));
  59. return result;
  60. }
  61. private void InitType(MethodCallExpression exp)
  62. {
  63. foreach (var arg in (exp.Arguments[0] as LambdaExpression).Parameters)
  64. {
  65. if (this.Context.InitMappingInfo != null)
  66. {
  67. this.Context.InitMappingInfo(arg.Type);
  68. this.Context.RefreshMapping();
  69. }
  70. }
  71. }
  72. }
  73. }